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.

運行出來的結果是:

到此爲止,這本書裏面的例子都能正確的運行。但是後面一個例子就出現報錯,還未找到解決方法,會在下篇文章中提出。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章