Esp*_*nda 2 python forms encoding utf-8 bottle
我正在尝试使用 Bottle.py 从网页中的用户获取输入信息。
一切正常,除非我有拉丁字符(主要是口音)。我尝试在代码的前两行使用 utf-8 和 latin-1 编码,但它不起作用。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bottle
@bottle.post('/newpost')
def post_newpost():
subject = bottle.request.forms.get("subject")
body = bottle.request.forms.get("body")
tags = bottle.request.forms.get("tags")
Run Code Online (Sandbox Code Playgroud)
页面中的html代码是:
<html>
<head>
<meta charset="utf-8" />
<title>New Posts</title>
</head>
<body>
<form action="/newpost" method="POST">
<h2>Post title</h2>
<input type="text" name="subject" size="120" value="{{subject}}" ><br>
<h2>Post<h2>
<textarea name="body" cols="120" rows="20">{{body}}</textarea><br>
<h2>Tags</h2>
<input type="text" name="tags" size="120" value="{{tags}}"><br>
<p>
<input type="submit" value="Submit">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我在 Bottle 页面上读到:
在 Python 3 中,所有字符串都是 unicode,但 HTTP 是基于字节的有线协议。在将字节字符串传递给应用程序之前,服务器必须以某种方式对其进行解码。为了安全起见,WSGI 建议使用 ISO-8859-1(又名 latin1),这是一种可逆的单字节编解码器,以后可以使用不同的编码进行重新编码。Bottle 为 FormsDict.getunicode() 和属性访问执行此操作,但不适用于 dict-access 方法。这些返回服务器实现提供的未更改值,这可能不是您想要的。
request.query['城市']
'Göttingen' # 一个 utf8 字符串被服务器临时解码为 ISO-8859-1
request.query.city
'Göttingen' # 相同的字符串被 Bottle 正确地重新编码为 utf8
如果您需要具有正确解码值的整个字典(例如对于 WTForms),您可以调用 FormsDict.decode() 以获取重新编码的副本。
阅读后,我尝试使用该功能,但不知道如何使用。现在 Bottle 形式返回字符串,所以我不能使用 encode('utf-8') 或 decode('utf-8')。
请帮我!
谢谢!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bottle
@bottle.post('/newpost')
def post_newpost():
subject = bottle.request.forms.subject
body = bottle.request.forms.body
tags = bottle.request.forms.tags
Run Code Online (Sandbox Code Playgroud)
这样就可以了....谢谢!