How to display GAE Query object contents and structure?
I want to print out the structure of a Query object, similar to how you can print out the contents of a dict or list at the interactive python prompt. I've found I'm having trouble visualizing what the data structures look like, which of course makes passing in template arguments much harder.
For example, here is a very simple UserProfile db class, and me attempting to print out all profiles, and the contents of the second profile.
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
class UserProfile(db.Model):
user = db.UserProperty(auto_current_user_add=True)
name = db.StringProperty()
class TestHandlerBasic(webapp.RequestHandler):
def get(self):
profiles = UserProfile.all()
self.response.out.write('The whole profiles: ')
self.response.out.write(profiles)
self.response.out.write('<p>')
self.response.out.write('Now, print out all profiles: <p>')
for profile in profiles:
self.response.out.write(profile.user)
self.response.out.write('<br>')开发者_如何学JAVA
self.response.out.write('<p>')
self.response.out.write('There are this many profiles: ')
self.response.out.write(profiles.count())
self.response.out.write('<p>This is the second profile profiles[1]: ')
self.response.out.write(profiles[1])
return
application = webapp.WSGIApplication([(r'/testbasic', TestHandlerBasic),] debug=True)
I get this kind of output:
The whole profiles:
Now, print out all profiles:
test@example.com
ard@example.comThere are this many profiles: 2
This is the second profile profiles[1]:
After the first line I get <google.appengine.ext.db.Query object at 0x490bd10>
and the last line I get <models.UserProfile object at 0x490bb90>
, as well. So, how do I print out a dump of the Query object or models object?
Query objects don't themselves hold any db.Model entities they are returned by get()
or fetch()
. So you would have to to switch UserProfile.all()
for something like:
profiles = UserProfile.all().fetch(1000)
Personally I like to subclass the db.Model class and add a few conveniences for serialising my models. I do this mainly so I can get quick JSON representations of entities, but it's quite handy for dumping/inspecting them too.
Here's an example of my BaseModel extension that adds __dict__
and __json__
methods to entities. If you also added an __repr__
that dumps the __dict__
method you could improve the string representation of the entities when they are printed to the console.
精彩评论