通过 python 2.7、cgi 和 html post 将 Å、Ä 和 Ö 添加到 sqlite table

Adding Å,Ä and Ö to sqlite table through python 2.7, cgi and html post

我正在使用 cgi、python 2.7 和 sqlite。

我要插入一个字符串?包含字符 å、ä 和 ö 到 sqlite table.

字符串取自 html post 使用 cgi

这段代码取值:

print '<form action="./printusername.cgi" method="post">'
print 'First Name: <input type="text" name="first_name">'
print '</form>'

我正在像这样接收 printusername.cgi 中的值:

import cgi
cgitb.enable()
form = cgi.FieldStorage() 
first_name = form.getvalue('first_name')

然后我试图将它传递给 sqlite table,以及一些其他值,如下所示:

import sqlite3
con = sqlite3.connect('Addressbook.db')
cursor = con.cursor()
contact = (first_name,other_valu_1,other_valu_1)
cursor.execute("INSERT INTO entrys VALUES(?, ?, ?)",contact)

当我这样做时,我会收到以下错误:

<class 'sqlite3.ProgrammingError'>: You must not use 8-bit bytestrings
unless you use a text_factory that can interpret 8-bit bytestrings
(like text_factory = str). It is highly recommended that you instead
just switch your application to Unicode strings. 

如果我不在 html post 中使用 å、ä 或 ö,一切正常。

为什么会出现这个错误?我怎样才能避免它并仍然保持 sqlite table 中的数据可读?

如果数据需要格式化,下次访问时如何格式化回来?

感谢所有帮助! sry 4 我的英语不好。

您的浏览器将编码的字符串发送到服务器。它使用什么编码取决于原始网页的编码方式,但通常是指 UTF-8。您需要使用该编码将这些值解码为unicodeobjects。

最好的办法是通过将内容编码添加到 Content-Type header:

来告诉浏览器在发送 HTML 表单时使用什么编解码器
print 'Content-Type: text/html; charset=utf-8'

然后在收到数据后,尝试解码数据:

try:
    first_name = form.getvalue('first_name').decode('utf8')
except (AttributeError, UnicodeDecodeError):
    # Could not decode or there was no such field
    # Handle the error.

您可能需要阅读 Python 和 Unicode: