python wsgi网络编程2

阅读《The Quick Python Book 2nd》


creating a message wall

基本功能:信息存储在sqlite3数据库中;URL是用于暗示需要查询的user和tags

附加功能:增加一个表,这需要send HTML code来建表;当用户提交表时能取回表值。这里使用 a StringIO object 来输出结果。

                  取回表值仅发生在表值被提交的时候,所以请求者的REQUEST_METHOD是POST。我们通过environ的CONTENT_LENGTH得知表串的大小,然后从environ中的wsgi.input中读取。


1> creating the database

   messages table:包括3个属性(user, message, timestramp)。user和message是sqlite3中的text,是python中的string。timestamp是pythondatetime。


2> creating an application object

# message_wall02.py

from __future__ import print_function
from wsgiref.simple_server import make_server
#from io import StringIO
from StringIO import StringIO


def message_wall_app(environ, start_response):
    output = StringIO()
    status = b'200 OK' #HTTP Status
    headers = [(b'Content_type', b'text/html; charset=utf-8')]
    start_response(status,headers)

    print("<h1>Message Wall</h1>", file=output)
    if environ['REQUEST_METHOD'] == 'POST':
        size = int (environ['CONTENT_LENGTH'])
        post_str=environ['wsgi.input'].read(size)
        print(post_str, "<p>", file=output)
    print('<form method="POST">User: <input type="text" '
          'name="user">Message: <input type="text" '
          'name="message"><input type="submit" value="Send"></form>', file=output)
    return [output.getvalue()]

httpd = make_server('', 8000, message_wall_app)
print("Serving on port 8000...")

httpd.serve_forever()

这里值得注意的是:上述代码是在python2.7.3中运行的,所以与书中的代码有所不同。

代码的开头:

1> If you want to use the print function in Python 2, you have to import from __future__:

from __future__ import print_function

2> io.StringIO is a class. It handles Unicode. It reflects the preferred Python 3 library structure.

StringIO.StringIO is a class. It handles strings. It reflects the legacy Python 2 library structure.

运行出来的结果是:

到此为止,这本书里面的例子都能正确的运行。但是后面一个例子就出现报错,还未找到解决方法,会在下篇文章中提出。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值