"Web.py - Unicode: Decode(utf-8) gives"

2024-06-02 09:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

def search(str):
    cnx = mysql.connector.connect(user='arda', password='1', database='worddb')
    cursor = cnx.cursor()
    sqlq = "SELECT COUNT(1) FROM names WHERE name = '%s'" %str
    cursor.execute(sqlq)
    if cursor.fetchone()[0]:
        return str + " " + "name"
    else:
        return str + " " + "not name"

当我搜索Ömür时,它给我的输出是ömür

  1. 我声明了编码:utf-8--

2-尝试过str.decode("utf-8")

还创建了我的8-utf数据库

当我尝试的时候str.解码它给出了ascii错误:

^{pr2}$

我的代码怎么了?在


Tags: namesearchconnectorreturndefconnectmysqlpassword
1条回答
网友
1楼 · 发布于 2024-06-02 09:31:38

来自数据库的响应已经是Unicode。我们必须假设网页.py响应时将其编码为UTF-8。在

因此,您需要添加一个Content-Type头,并将charset设置为utf-8,这样浏览器就知道页面的编码了。在

例如

web.header('Content-Type','text/html; charset=utf-8', unique=True)

完整示例:

^{pr2}$

相关问题 更多 >