About
RSS

Bit Focus


GAE 速成简易博客 - 表单处理与数据存取

Posted at 2012-01-19 03:31:17 | Updated at 2024-04-19 02:02:38

上节回顾 - 站点基本配置与模板

没有数据滋养的首页还是个半残废, 下面开始折腾数据库.

添加文章

入口

    虽然添加文章这种事情可以直接通过后台暴力搞数据库来做, 但既然要写的是 Web 应用, 那么写个页面提供添加文章的入口也是理所当然的事情.
    页面嘛, 肯定得有个 HTML 模板撑着, 来建个文件, templates/add_post.html
<html>
<head><title>Add Post</title></head>
<body>
<form>
<table>
<tr><td>Title</td><td><input type='text' name='title'></td></tr>
<tr><td style='vertical-align: top;'>Content</td>
    <td><textarea name='content'></textarea></td></tr>
<tr><td><input type='submit'/></td></tr>
</table>
</form>
    接下来得增加一个 RequestHandler, 新建文件 add_post.py
from 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()))
    这个文件看起来与 index.py 差不多, 只不过因为 add_post.html 不需要参数, 因此传入 render 的字典是空字典.

    最后在 main.py 中新增一项, 将一个 URL 映射到 AddPostEntry
import 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)
    现在访问 http://localhost:8080/add_post/, 就可以看到这个入口页面了. 不过因为表单还没有设置处理者, 因此点破提交按钮就没有反应的.

处理表单

    还是得添加一个处理请求的类, 修改 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')
    假设现在采用 HTTP Post 方法来处理请求 (Get 请求只适合处理一些简短的参数, 而一篇博客文章的内容很可能太长而无法放进请求 URL 中; 此外, HTTP 规定 Get 应该是对服务器的轻微操作, 无毒害无副作用, 因此这种可能会修改站点数据库的操作还是免了), 而这时应该写 post(self) 函数.
    在函数中新建了一个 model.Post 对象, 并且从 HTTP 请求的参数中找到 titlecontent 赋值给这个对象, 然后调用 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)
    接下来, 再去把 templates/add_post.html 里的表单给改好
<form action='/add_post_do' method='post'>
<table>
<tr><td>Title</td><td><input type='text' name='title'></td></tr>
<tr><td style='vertical-align: top;'>Content</td>
    <td><textarea name='content'></textarea></td></tr>
<tr><td><input type='submit'/></td></tr>
</table>
</form>
    现在添加文章的功能就完成了. 访问 http://localhost:8080/add_post/ 添加一篇文章吧.

    可是, 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,
            }))
    GQL 是 Google 提供的一种类似 SQL 的查询语句, 在上面的代码中, 通过 GQL 查到全部 Post, 然后传入 render 函数. 现在再访问首页, 即可看到刚才添加的文章了.

下节预告 - 进阶数据库操作

Post tags:   Web Server  Tutorial  Google AppEngine  Python

Leave a comment:




Creative Commons License Your comment will be licensed under
CC-NC-ND 3.0


. Back to Bit Focus
NijiPress - Copyright (C) Neuron Teckid @ Bit Focus
About this site