本帖最后由 sinanjj 于 2010-8-27 22:36 编辑
http://code.google.com/appengine ... usingdatastore.html
Using the Datastore
使用datastore
A Complete Example Using the Datastore
使用datastore的例子
from google.appengine.ext import db
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
for greeting in greetings:
if greeting.author:
self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
else:
self.response.out.write('An anonymous person wrote:')
self.response.out.write('<blockquote>%s</blockquote>' %
cgi.escape(greeting.content))
# Write the submission form and the footer of the page
self.response.out.write("""
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</body>
</html>""")
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
application = webapp.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Storing the Submitted Greetings
保存提交的greetings
App Engine includes a data modeling API for Python. It's similar to Django's data modeling API, but uses App Engine's scalable datastore behind the scenes.
gap包含一个操作数据模型的api, 类似django的数据模型api.
For the guestbook application, we want to store greetings posted by users. Each greeting includes the author's name, the message content, and the date and time the message was posted so we can display messages in chronological order.
在这个例子中, 我们意图保存每一条问候语句, 包含问候着名字, 信息内容, 数据, 时间.
To use the data modeling API, import the google.appengine.ext.db module:
第一步先引入google model api:
from google.appengine.ext import db
The following defines a data model for a greeting:
针对问候定义一个数据模型:
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
This defines a Greeting model with three properties: author whose value is a User object, content whose value is a string, and date whose value is a datetime.datetime.
这个定义的模型包含了3个数据条目: author, 属性是用户类, content, 是个字符串, data是个时间类
Some property constructors take parameters to further configure their behavior. Giving the db.StringProperty constructor the multiline=True parameter says that values for this property can contain newline characters. Giving the db.DateTimeProperty constructor a auto_now_add=True parameter configures the model to automatically give new objects a date of the time the object is created, if the application doesn't otherwise provide a value. For a complete list of property types and their options, see the Datastore reference.
Now that we have a data model for greetings, the application can use the model to create new Greeting objects and put them into the datastore. The following new version of the Guestbook handler creates new greetings and saves them to the datastore:
下面当然是使用这个新定义的模型来放入
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
This new Guestbook handler creates a new Greeting object, then sets its author and content properties with the data posted by the user. It does not set the date property, so date is automatically set to "now," as we configured the model to do.
在guestbook处理函数中, 创建了一个新的greeting对象, 然后设置它的anthor和content属性. 时间属性会自动设置为当前时间.
Finally, greeting.put() saves our new object to the datastore. If we acquired this object from a query, put() would update the existing object. Since we created this object with the model constructor, put() adds the new object to the datastore.
最后, greeting.put()保存这个新建立的对象到datastore. 如果我们从一次查询中得到的这个对象, pur()方法将更新现存的对象.
Retrieving the Stored Greetings With GQL
使用gql将存放的greeting对象取出来
The App Engine datastore has a sophisticated query engine for data models. Because the App Engine datastore is not a traditional relational database, queries are not specified using SQL. Instead, you can prepare queries using a SQL-like query language we call GQL. GQL provides access to the App Engine datastore query engine's features using a familiar syntax.
gae使用的datastore是google自己开发的, 非常规关系数据库(传说是no-sql类hash表云存储), 所以你也别指望用sql啦. 这里有个类似的, gql.
The query happens on this line:
查询发生在这一行:
greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
Alternatively, you can call the gql(...) method on the Greeting class, and omit the SELECT * FROM Greeting from the query:
达到同样的目的你可以使用如下语句
greetings = Greeting.gql("ORDER BY date DESC LIMIT 10")
A GQL query can have a WHERE clause that filters the result set by one or more conditions based on property values. Unlike SQL, GQL queries may not contain value constants: Instead, GQL uses parameter binding for all values in queries. For example, to get only the greetings posted by the current user:
过滤: 下边是一个过滤出当年用户的例子
if users.get_current_user():
greetings = Greeting.gql("WHERE author = :1 ORDER BY date DESC",
users.get_current_user())
You can also use named parameters instead of positional parameters:
greetings = Greeting.gql("WHERE author = :author ORDER BY date DESC",
author=users.get_current_user())
For a complete description of GQL and the query APIs, see the Datastore reference.
Clearing the Development Server Datastore
The development web server uses a local version of the datastore for testing your application, using temporary files. The data persists as long as the temporary files exist, and the web server does not reset these files unless you ask it to do so.
If you want the development server to erase its datastore prior to starting up, use the --clear_datastore option when starting the server:
用如下命令清空本地的测试datastore:
dev_appserver.py --clear_datastore helloworld/ |