Including GqlQuery result set in python dictionary

Say I have a model like this

class Foo(db.Model):
    id = db.StringProperty()
    bar = db.StringProperty()
    baz = db.StringProperty()

And I'm going to GqlQuery like this

foos = db.GqlQuery("SELECT * FROM Foo")

I want to take the GqlQuery results and turn into some kind of JSON string that I can manipulate from different languages.


This is how i do it now

  • Add a method to the Foo class that converts it to a dictionary

    def toDict(self):
        return {
             'id': self.id,
             'bar': self.bar,
             'baz': self'baz
           }
    
  • Scroll through the GqlQuery results and manually add each instance of Foo to the dictionary

    fooDict = {}
    
    for foo in foos:
        fooDict[foo.id] = foo.toDict()
    
    return simplejson.dumps(fooDict)
    

My approach above works, but it feels rude.

Is there a cleaner, more β€œpythonic” way to handle this?

The end format does not have to be exactly what I did above. It just needs to be something that translates well to JSON, so I can handle it from Javascript / PHP / whatever.

+3
4

google.appengine.api.datastore. API- datastore , google.appengine.ext.db, Entity, dict. GQL google.appengine.ext.gql ( ) Query, GQL . Query api.datastore , ( Entity ).

"datastore.Query(" Foo "). all()".

+2

, :

class Foo:
    id = db.StringProperty() # etc.
    json_attrs = 'id bar baz'.split()

# Depending on how easy it is to identify string properties, there
# might also be a way to assign json_attrs programmatically after the
# definition of Foo, like this
Foo.json_attrs = [attr for attr in dir(Foo)
                  if isStringProperty(getattr(Foo, attr))]

fooDict=dict((foo.id,dict(getattr(foo, attr)
                          for attr in Foo.json_attrs))
              for foo in foos)
+1

http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55

The coding method will solve your GQL-to-JSON needs. I would recommend getting rid of some redundant datetime options .... time as an era? in fact?

0
source

You can use web2py for GAE and do:

db.define_table('foo',SQLField('bar'),SQLField('baz'))
rows=db(db.foo.id>0).select()
### rows is a list, rows.response is a list of tuples
for row in rows: print  dict(row)

Also works with Oracle, Postgresql, Mssql, mysql, etc.

-1
source

Source: https://habr.com/ru/post/1698400/


All Articles