- 论坛徽章:
- 0
|
本帖最后由 iscien 于 2013-06-09 20:59 编辑
刚学习python 3 和bottle ,在python 3.3.2,bottle 0.11.6,Win7的环境下写了一个测试程序,但在总出现乱码,请大伙帮忙解决,多谢。- # -*- coding: utf-8 -*-
- #中文测试一下
- import bottle
- #import peewee
- from bottle import route, run, get, post, request
- @route('/')
- def hello():
- return "Hello World! 你好世界"
- @get('/login')
- def login_form():
- return """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
- </head>
- <body>
- <form method="POST" action="/login">
- <input name="name" type="text" />
- <input name="password" type="password" />
- <input type="submit" />
- </form>
- </body>
- </html>"""
- @post('/login')
- def login_submit():
- name = request.forms.get('name')
- password = request.forms.get('password')
- #print(name,type(name),"张三")
-
- return """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
- </head>
- <body>
- name: %s , password: %s, 其它:%s
- </body>
- </html>""" %(name,password,"张三")
- run(host='localhost', port=8080, debug=True)
复制代码
B-Todo.7z
(715 Bytes, 下载次数: 1)
通过- name = request.forms.get('name')
复制代码 得到的是bytes,而不是unicode str
应该使用- name = request.forms.getunicode('name')
复制代码 或者直接- name = request.forms.name
复制代码 详细解释见http://bottlepy.org/docs/dev/tutorial.html,关于"WTForms support"的部分。
Note
In Python 2 all keys and values are byte-strings. If you need unicode, you can call FormsDict.getunicode() or fetch values via attribute access. Both methods try to decode the string (default: utf and return an empty string if that fails. No need to catch UnicodeError:
>>> request.query['city']
'G\xc3\xb6ttingen' # A utf8 byte string
>>> request.query.city
u'Göttingen' # The same string as unicode
In Python 3 all strings are unicode, but HTTP is a byte-based wire protocol. The server has to decode the byte strings somehow before they are passed to the application. To be on the safe side, WSGI suggests ISO-8859-1 (aka latin1), a reversible single-byte codec that can be re-encoded with a different encoding later. Bottle does that for FormsDict.getunicode() and attribute access, but not for the dict-access methods. These return the unchanged values as provided by the server implementation, which is probably not what you want.
>>> request.query['city']
'Göttingen' # An utf8 string provisionally decoded as ISO-8859-1 by the server
>>> request.query.city
'Göttingen' # The same string correctly re-encoded as utf8 by bottle
If you need the whole dictionary with correctly decoded values (e.g. for WTForms), you can call FormsDict.decode() to get a re-encoded copy. |
|