python-3.x - cgi python3 编码问题

标签 python-3.x character-encoding cgi

我创建了一个cgi脚本(使用apache在本地主机上运行),它将从textarea加载文本,然后我将使用它。我对 š、ť、é、.. 等字符有问题,它们无法正确显示。我尝试了很多方法。这是我的短代码的一个版本,我只是在其中寻找正确的处理方法。

#!C:/Python33/python 
# -*- coding: UTF-8 -*-
 
import cgi
import cgitb

cgitb.enable()

form = cgi.FieldStorage()
if form.getvalue('textcontent'):
   text_content = form.getvalue('textcontent')
else:
   text_content = ""


print ("Content-type:text/html")
print ()
print("<!DOCTYPE html>")
print ("<html>")
print ("<head>")
print("<meta charset='UTF-8'></meta>")
print ("</head>")
print ("<body>")
print ("<form>")
print ("text_area:<br />")
print ("<textarea name='textcontent' rows='5' cols='20'></textarea>")
print ("<br />")
print ("<input type='submit' value='submit form' />")
print ("</form>")
print("<p>")
print(text_content) 
print("</p>")
print ("</body>")
print ("</html>")

这种方式使用UTF-8,当我尝试写一些东西时,它看起来像这样(写入textarea并提交):

čítam -> ��tam

当我在 html 部分使用 latin-1 作为 python 编码和 utf-8 作为字符集时,它的工作原理如下:

časa -> časa (correctly)

但对于带有重音符号的字符(例如 áno),它会返回错误:

UnicodeEncodeError: 'charmap' codec can't encode character '\\ufffd' in position 0: character maps to <undefined>\r

使用sys.stdout.encoding,它写入cp1250编码(在Windows下工作),使用sys.getdefaultencoding(),它返回utf-8

我还尝试了 text_content = (form.getvalue('textcontent')).encode('utf-8') 例如单词 číslo ,结果是 b'\xef\xbf\xbd\xef\xbf\xbdslo'

我不知道如何处理这个问题。

我需要 číslo -> číslo 作为示例。

更新:现在我有 python 的 UTF-8 作为 html 编码。看起来文本处理(将单词与字典进行比较,..)进展顺利,所以现在唯一的问题是输出看起来像 ��tam,所以我需要将其修改为看起来像 čítam 而不是 ��tam .

更新2:当编码为UTF-8并且在浏览器UTF-8中时,它显示�s,当我将浏览器编码更改为cp1250时,它显示正确,但是当我刷新站点或单击“提交”按钮时,它显示写入错误 UnicodeEncodeError: 'charmap' 编解码器无法编码字符 '\\ufffd'

更新3:在linux上尝试过,遇到一些问题后我发现apache服务器使用了错误的编码(ascii),但我还无法解决这个问题。将 /etc/apache2/envvars 修改为 PATH LANG="sk_SK.UTF-8"但 gedit 在终端中收到一些警告,表明编辑效果不好。所以编码还是ascii。

最佳答案

以这种方式编写表单:

<form accept-charset="utf-8">

在表单中添加accept-charset = "utf-8",可以解决这个问题

关于python-3.x - cgi python3 编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23382318/

相关文章:

security - 最大熵的最小密码长度

python-3.x - 如果我有AMD显卡,如何使用tensorflow-gpu版本?

python-3.x - Azure DevOps 的客户端凭据流程

python - 从张量中提取多个子矩阵

php - 带有ajax响应的奇怪编码

javascript - window.open() 后字符编码发生变化

perl - mod_perl 处理包含路径的方式与 cgi 不同?

Python/CGI - 上传文件尝试返回空页面

python - 当参数可能非常大时进行内存

linux - 无法将信号发送到perl中的另一个进程