阅读《The Quick Python Book 2nd》
本节的例子运行出错,希望各位大神帮忙解决下!
在上篇文章的程序 message_wall02.py能实现的功能的基础上,加入一个新的功能,“保存表格的内容”。
为了实现这个功能,我们需要从表格中读取,然后使用 sqlite3 query将它保存在数据库中。加入一个方程,它将表格字符串解析成一个字典,并加入当前的timestamp到该字典,该字典用于SQL query的参数来将信息保存到数据库。
# message_wall03.py python2
from __future__ import print_function
from wsgiref.simple_server import make_server
#from io import StringIO
from StringIO import StringIO
import sqlite3
import datetime
in post_str.decode().split("&")}
return form_vals
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)
form_vals = get_form_vals(post_str)
form_vals['timestamp'] = datetime.datetime.now()
print(form_vals,"<p>", file=output)
cursor.execute("insert into messages(user,message,ts) values "
"(:user, :message, :timestamp)",form_vals)
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...")
conn = sqlite3.connect("messagefile")
cursor=conn.cursor()
httpd.serve_forever()
运行python message_wall03.py。此时,默认情况下是用python2.7.3, 然后就出错了,不知道什么原因。
接着,我安装了python3,并使用书中的源代码。其实就是代码开头不同:
# message_wall03.py python3
#from __future__ import print_function
from wsgiref.simple_server import make_server
from io import StringIO
#from StringIO import StringIO
import sqlite3
import datetime
后面一样
运行 python3 message_wall03.py,然后出错。不知道什么原因。
在goole上看到这篇博客http://phyeas.iteye.com/blog/354178,也是初试python3的各种错误。