从数据存储中提取数据并在python中的Json中将其转换(Google Appengine) [英] Pulling data from datastore and converting it in Json in python(Google Appengine)

查看:49
本文介绍了从数据存储中提取数据并在python中的Json中将其转换(Google Appengine)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Appengine创建一个应用,其中我从网站上获取数据并将其存储在数据库(数据存储)中.现在,只要用户按"application_url \ name = xyz&; city = abc",我正在从数据库中获取数据,并希望将其显示为json.现在,我正在使用过滤器来获取基于名称和城市的数据,但输出为 [].我不知道如何从中获取数据.我的代码如下:

I am creating an apllication using google appengine, in which i am fetching a data from the website and storing it in my Database (Data store).Now whenever user hits my application url as "application_url\name =xyz&city= abc",i am fetching the data from the DB and want to show it as json.Right now i am using a filter to fetch data based on the name and city but getting output as [].I dont know how to get data from this.My code looks like this:

class MainHandler(webapp2.RequestHandler):
    def get(self):
        commodityname = self.request.get('veg',"Not supplied")
        market = self.request.get('market',"No market found with this name")
        self.response.write(commodityname)
        self.response.write(market)
        query = commoditydata.all()
        logging.info(commodityname)
        query.filter('commodity = ', commodityname)
        result = query.fetch(limit = 1)
        logging.info(result)

商品数据"表的db结构为

and the db structure for "commoditydata" table is

class commoditydata(db.Model):
        commodity= db.StringProperty()
        market= db.StringProperty()
        arrival= db.StringProperty()
        variety= db.StringProperty()
        minprice= db.StringProperty()
        maxprice= db.StringProperty()
        modalprice= db.StringProperty()
        reporteddate= db.DateTimeProperty(auto_now_add = True)

谁能告诉我如何使用名称和市场从db中获取数据并在Json中进行隐蔽.首先要从db中获取数据是优先事项.任何建议都将很有用.

Can anyone tell me how to get data from the db using name and market and covert it in Json.First getting data from db is the more priority.Any suggestions will be of great use.

推荐答案

如果您要开始使用新应用,我建议您使用

If you are starting with a new app, I would suggest to use the NDB API rather than the old DB API. Your code would look almost the same though.

据我从您的代码示例可以看出,只要请求中的HTTP查询参数与数据存储区中的实体对象匹配,查询就应为您提供结果.

As far as I can tell from your code sample, the query should give you results as far as the HTTP query parameters from the request would match entity objects in the datastore.

我可以想到导致空结果的一些可能原因:

I can think of some possible reasons for the empty result:

  • 您只认为输出为空,因为您太早使用了 write()了;应用程序引擎不支持响应流,您必须一次性编写所有内容,并在查询数据存储区后执行此操作
  • 您要过滤的属性尚未在数据存储区中建立索引,至少没有为您要查找的实体建立索引
  • 过滤器什么都没有匹配(请在日志中查看您从请求中获得的值)
  • 您的查询使用的命名空间与存储数据的位置不同(但是,如果您未在任何地方显式设置命名空间,则不太可能)
  • you only think the output is empty, because you use write() too early; app-engine doesn't support streaming of response, you must write everything in one go and you should do this after you queried the datastore
  • the properties you are filtering are not indexed (yet) in the datastore, at least not for the entities you were looking for
  • the filters are just not matching anything (check the log for the values you got from the request)
  • your query uses a namespace different from where the data was stored in (but this is unlikely if you haven't explicitly set namespaces anywhere)

在Cloud Developer Console中,您可以查询数据存储,甚至可以应用过滤器,因此无需编写实际代码即可看到结果.

In the Cloud Developer Console you can query your datastore and even apply filters, so you can see the results with-out writing actual code.

  1. 转到 https://console.developers.google.com
  2. 在左侧,选择存储> Cloud Datastore>查询
  3. 选择名称空间(默认应该可以)
  4. 选择种类商品数据"
  5. 添加带有您期望从请求中获得的示例值的过滤器,并查看获得了多少结果

还可以查看 Monitoring> Log ,它与您的 logging.info()调用一起真正有助于更好地了解请求期间的情况.

Also look into Monitoring > Log which together with your logging.info() calls is really helpful to better understand what is going on during a request.

一旦获得数据,向JSON的转换就相当容易.在您的请求处理程序中,创建一个空的词典列表.对于从查询结果中获得的每个对象:设置要发送的属性,在dict中定义一个键,然后将该值设置为从数据存储中获得的值.最后,将字典作为JSON字符串转储.

The conversion to JSON is rather easy, once you got your data. In your request handler, create an empty list of dictionaries. For each object you get from the query result: set the properties you want to send, define a key in the dict and set the value to the value you got from the datastore. At the end dump the dictionary as JSON string.

class MainHandler(webapp2.RequestHandler):
    def get(self):
        commodityname = self.request.get('veg')
        market = self.request.get('market')
        if commodityname is None and market is None:
            # the request will be complete after this:
            self.response.out.write("Please supply filters!")
        # everything ok, try query:
        query = commoditydata.all()
        logging.info(commodityname)
        query.filter('commodity = ', commodityname)
        result = query.fetch(limit = 1)
        logging.info(result)
        # now build the JSON payload for the response
        dicts = []
        for match in result:
            dicts.append({'market': match.market, 'reporteddate': match.reporteddate})
        # set the appropriate header of the response:
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        # convert everything into a JSON string    
        import json
        jsonString = json.dumps(dicts)
        self.response.out.write( jsonString )

这篇关于从数据存储中提取数据并在python中的Json中将其转换(Google Appengine)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆