Google App Engine 数据存储区使用 Python 查询 JSON

发布于 2024-10-25 23:52:16 字数 313 浏览 5 评论 0原文

如何通过 Google App Engine 数据存储获取数据来获取 python 中的 JSON 对象?

我在数据存储区中有包含以下字段的模型:

id
key_name
object
userid
created

现在我想获取一个用户的所有对象:

query = Model.all().filter('userid', user.user_id())

如何从查询创建一个 JSON 对象以便我可以编写它?

我想通过 AJAX 调用获取数据。

How can I get a JSON Object in python from getting data via Google App Engine Datastore?

I've got model in datastore with following field:

id
key_name
object
userid
created

Now I want to get all objects for one user:

query = Model.all().filter('userid', user.user_id())

How can I create a JSON object from the query so that I can write it?

I want to get the data via AJAX call.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅语花开 2024-11-01 23:52:16

不确定您是否得到了您正在寻找的答案,但是您的意思是如何将 Query 对象中的模型(条目)数据直接解析为 JSON 对象? (至少那是我一直在寻找的)。

我编写此代码是为了将 Query 对象中的条目解析为 JSON 对象列表:

def gql_json_parser(query_obj):
    result = []
    for entry in query_obj:
        result.append(dict([(p, unicode(getattr(entry, p))) for p in entry.properties()]))
    return result

您可以让您的应用程序通过使用 simplejson 进行编码来响应 AJAX 请求,例如:

query_data = MyModel.all()
json_query_data = gql_json_parser(query_data)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(simplejson.dumps(json_query_data))

您的应用程序将返回如下内容:

[{'property1': 'value1', 'property2': 'value2'}, ...]

让我知道这是否有帮助!

Not sure if you got the answer you were looking for, but did you mean how to parse the model (entry) data in the Query object directly into a JSON object? (At least that's what I've been searching for).

I wrote this to parse the entries from Query object into a list of JSON objects:

def gql_json_parser(query_obj):
    result = []
    for entry in query_obj:
        result.append(dict([(p, unicode(getattr(entry, p))) for p in entry.properties()]))
    return result

You can have your app respond to AJAX requests by encoding it with simplejson e.g.:

query_data = MyModel.all()
json_query_data = gql_json_parser(query_data)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(simplejson.dumps(json_query_data))

Your app will return something like this:

[{'property1': 'value1', 'property2': 'value2'}, ...]

Let me know if this helps!

只为守护你 2024-11-01 23:52:16

如果我理解正确的话,我已经实现了一个像这样工作的系统。听起来您想在 GAE 数据存储模型中存储任意 JSON 对象。为此,您需要在进入数据库时​​将 JSON 编码为某种字符串,并在退出时将其从字符串解码为 Python 数据结构。您将需要使用 JSON 编码器/解码器来执行此操作。我认为 GAE 基础设施包括一个。例如,您可以使用“包装类”来处理编码/解码。沿着这些思路......

class InnerClass(db.Model):
    jsonText = db.TextProperty()
    def parse(self):
        return OuterClass(self)

class Wrapper:
    def __init__(self, storage=None):
        self.storage = storage
        self.json = None
        if storage is not None:
            self.json = fromJsonString(storage.jsonText)
    def put(self):
        jsonText  = ToJsonString(self.json)
        if self.storage is None:
            self.storage = InnerClass()
        self.storage.jsonText = jsonText
        self.storage.put()

然后总是对解析的包装对象而不是内部类

def getall():
    all = db.GqlQuery("SELECT * FROM InnerClass")
    for x in all:
        yield x.parse()

(未经测试)进行操作。请参阅 datastoreview.py 了解一些模型实现像这样工作。

If I understood you correctly I have implemented a system that works something like this. It sounds like you want to store an arbitrary JSON object in a GAE datastore model. To do this you need to encode the JSON into a string of some sort on the way into the database and decode it from a string into a python datastructure on the way out. You will need to use a JSON coder/decoder to do this. I think the GAE infrastructure includes one. For example you could use a "wrapper class" to handle the encoding/decoding. Something along these lines...

class InnerClass(db.Model):
    jsonText = db.TextProperty()
    def parse(self):
        return OuterClass(self)

class Wrapper:
    def __init__(self, storage=None):
        self.storage = storage
        self.json = None
        if storage is not None:
            self.json = fromJsonString(storage.jsonText)
    def put(self):
        jsonText  = ToJsonString(self.json)
        if self.storage is None:
            self.storage = InnerClass()
        self.storage.jsonText = jsonText
        self.storage.put()

Then always operate on parsed wrapper objects instead of the inner class

def getall():
    all = db.GqlQuery("SELECT * FROM InnerClass")
    for x in all:
        yield x.parse()

(untested). See datastoreview.py for some model implementations that work like this.

ヤ经典坏疍 2024-11-01 23:52:16

我执行了以下操作将 google 查询对象转换为 json。我也使用了上面 jql_json_parser 中的逻辑,除了所有内容都转换为 unicode 的部分。我想保留整数、浮点数和空等数据类型。

import json
class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'isoformat'): #handles both date and datetime objects
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

class BaseResource(webapp2.RequestHandler):
    def to_json(self, gql_object):
        result = []
        for item in gql_object:
            result.append(dict([(p, getattr(item, p)) for p in item.properties()]))
        return json.dumps(result, cls=JSONEncoder)

现在您可以对 BaseResource 进行子类化并在 gql_object 上调用 self.to_json

I did the following to convert the google query object to json. I used the logic in jql_json_parser above as well except for the part where everything is converted to unicode. I want to preserve the data-types like integer, floats and null.

import json
class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'isoformat'): #handles both date and datetime objects
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

class BaseResource(webapp2.RequestHandler):
    def to_json(self, gql_object):
        result = []
        for item in gql_object:
            result.append(dict([(p, getattr(item, p)) for p in item.properties()]))
        return json.dumps(result, cls=JSONEncoder)

Now you can subclass BaseResource and call self.to_json on the gql_object

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文