没有数据滋养的首页还是个半残废, 下面开始折腾数据库.
添加文章
入口
虽然添加文章这种事情可以直接通过后台暴力搞数据库来做, 但既然要写的是 Web 应用, 那么写个页面提供添加文章的入口也是理所当然的事情.页面嘛, 肯定得有个 HTML 模板撑着, 来建个文件, templates/add_post.html
Add Post
Title
Content
RequestHandler, 新建文件 add_post.pyfrom google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import os
class AddPostEntry(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__),
                            'templates/add_post.html')
        self.response.out.write(template.render(path, dict()))
add_post.html 不需要参数, 因此传入 render 的字典是空字典.最后在 main.py 中新增一项, 将一个 URL 映射到
AddPostEntryimport wsgiref.handlers
from google.appengine.ext import webapp
import index
import add_post
if __name__ == '__main__':
    application = webapp.WSGIApplication([
        ('/', index.Index),
        ('/add_post', add_post.AddPostEntry),
    ], debug=True)
    wsgiref.handlers.CGIHandler().run(application)
处理表单
还是得添加一个处理请求的类, 修改 add_post.py, 加入这个类import model
class AddPostHandler(webapp.RequestHandler):
    def post(self):
        new_post = model.Post()
        new_post.title = self.request.get('title')
        new_post.content = self.request.get('content')
        new_post.put()
        self.redirect('/add_post')
post(self) 函数.在函数中新建了一个
model.Post 对象, 并且从 HTTP 请求的参数中找到 title 和 content 赋值给这个对象, 然后调用 put() 方法将这个新建的对象放入数据库中. 最后, 因为这只是一个数据库操作的请求, 没有实际的页面与之对应, 因此需要转到其它页面, 把它改成重定向到首页 self.redirect('/') 也是没问题的, 看自己喜好了.接下来添加一个 URL 映射到这个类, 转到 main.py
if __name__ == '__main__':
    application = webapp.WSGIApplication([
        ('/', index.Index),
        ('/add_post', add_post.AddPostEntry),
        ('/add_post_do', add_post.AddPostHandler),
    ], debug=True)
    wsgiref.handlers.CGIHandler().run(application)
Title
Content
可是,
index.Index 这家伙里面还是一潭死水般的内容呢. 没关系, 马上来改.取出文章
先使用最暴力最简单的方法, 从数据库中拖出全部Post 对象, 丢进主页面中from google.appengine.ext import db
class Index(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        posts = db.GqlQuery('SELECT * FROM Post')
        self.response.out.write(template.render(path, {
                'posts': posts,
            }))
Post, 然后传入 render 函数. 现在再访问首页, 即可看到刚才添加的文章了.下节预告 - 进阶数据库操作
