Python请求编码POST数据

The*_*ian 22 python python-2.7 python-requests

版本:Python 2.7.3

其他库:Python-Requests 1.2.3,jinja2(2.6)

我有一个脚本将数据提交到论坛,问题是非ascii字符显示为垃圾.例如AndréTéchiné这样的名字就像AndréTéchéé一样出现.

以下是数据的提交方式:

1)数据最初是从UTF-8编码的CSV文件加载的,如下所示:

entries = []
with codecs.open(filename, 'r', 'utf-8') as f:
    for row in unicode_csv_reader(f.readlines()[1:]):
        entries.append(dict(zip(csv_header, row)))
Run Code Online (Sandbox Code Playgroud)

unicode_csv_reader位于Python CSV文档页面的底部:http://docs.python.org/2/library/csv.html

当我在解释器中键入条目名称时,我将名称视为u'Andr\xe9 T\xe9chin\xe9'.

2)接下来我通过jinja2渲染数据:

tpl = tpl_env.get_template(u'forumpost.html')
rendered = tpl.render(entries=entries)
Run Code Online (Sandbox Code Playgroud)

当我输入在解释器中呈现的名称时,我再次看到相同的: u'Andr\xe9 T\xe9chin\xe9'

现在,如果我将渲染变量写入这样的文件名,它会正确显示:

with codecs.open('out.txt', 'a', 'utf-8') as f:
    f.write(rendered)
Run Code Online (Sandbox Code Playgroud)

但我必须把它发送到论坛:

3)在POST请求代码中我有:

params = {u'post': rendered}
headers = {u'content-type': u'application/x-www-form-urlencoded'}
session.post(posturl, data=params, headers=headers, cookies=session.cookies)
Run Code Online (Sandbox Code Playgroud)

session是一个请求会话.

并且在论坛帖子中显示了该名称.我尝试过以下方法:

  • 遗漏标题
  • 编码渲染为rendered.encode('utf-8')(相同结果)
  • rendered = urllib.quote_plus(渲染)(全部为%XY)

如果我输入rendered.encode('utf-8'),我会看到以下内容:

'Andr\xc3\xa9 T\xc3\xa9chin\xc3\xa9'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?谢谢.

jfs*_*jfs 28

您的客户端应该像应该的那样运行nc -l 8888,例如作为服务器运行并发出请求:

import requests

requests.post('http://localhost:8888', data={u'post': u'Andr\xe9 T\xe9chin\xe9'})
Run Code Online (Sandbox Code Playgroud)

说明:

POST / HTTP/1.1
Host: localhost:8888
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.2.3 CPython/2.7.3

post=Andr%C3%A9+T%C3%A9chin%C3%A9
Run Code Online (Sandbox Code Playgroud)

你可以检查它是否正确:

>>> import urllib
>>> urllib.unquote_plus(b"Andr%C3%A9+T%C3%A9chin%C3%A9").decode('utf-8')
u'Andr\xe9 T\xe9chin\xe9'
Run Code Online (Sandbox Code Playgroud)
  • 检查服务器是否正确解码了请求.您可以尝试指定charset:

    headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    
    Run Code Online (Sandbox Code Playgroud)

    正文只包含ascii字符,所以它不应该受到伤害,正确的服务器x-www-form-urlencoded无论如何都会忽略任何类型的参数.在URL编码的表单数据中查找血淋淋的细节

  • 检查问题不是显示假象,即值正确但显示不正确