求助,关于bottle +python 3 中文显示的问题。
刚学习python 3 和bottle ,在python 3.3.2,bottle 0.11.6,Win7的环境下写了一个测试程序,但在总出现乱码,请大伙帮忙解决,多谢。
python?3 bottle 中文 乱码
# -*- 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)
name = request.forms.get('name')
name = request.forms.getunicode('name')
name = request.forms.name
>>> 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.