我一直在从事一个基于django的Python 3项目。我正在尝试合并captcha。我选择了django-recaptcha,但不幸的是,这个包不能用于python3。所以试着为python3量身定做。我做了一些2to3的事情,并根据需要做了一些修改。除了url encoding for Request之外,一切看起来都很好。
下面的代码段会产生POST data should be bytes or an iterable of bytes. It cannot be of type str.异常。
def encode_if_necessary(s):
if isinstance(s, str):
return s.encode('utf-8')
return s
params = urllib.parse.urlencode({
'privatekey': encode_if_necessary(private_key),
'remoteip': encode_if_necessary(remoteip),
'challenge': encode_if_necessary(recaptcha_challenge_field),
'response': encode_if_necessary(recaptcha_response_field),
})
if use_ssl:
verify_url = "https://%s/recaptcha/api/verify" % VERIFY_SERVER
else:
verify_url = "http://%s/recaptcha/api/verify" % VERIFY_SERVER
request = urllib.request.Request(
url= verify_url,
data=params,
headers={
"Content-type": "application/x-www-form-urlencoded",
"User-agent": "reCAPTCHA Python"
}
)
httpresp = urllib.request.urlopen(request)所以我试着在request中对网址和其他东西进行编码-
request = urllib.request.Request(
url= encode_if_necessary(verify_url),
data=params,
headers={
"Content-type": encode_if_necessary("application/x-www-form-urlencoded"),
"User-agent": encode_if_necessary("reCAPTCHA Python")
}
)但这会产生urlopen error unknown url type: b'http异常。
有人知道怎么修吗?任何帮助都很感激:)。
发布于 2014-02-15 19:25:23
好的,我自己回答:P。
以python的官方文档的一个例子中的提示为例,我将data排除在Request之外,并分别将request and data传递给urlopen()。下面是更新的片段-
params = urllib.parse.urlencode({
'privatekey': encode_if_necessary(private_key),
'remoteip': encode_if_necessary(remoteip),
'challenge': encode_if_necessary(recaptcha_challenge_field),
'response': encode_if_necessary(recaptcha_response_field),
})
if use_ssl:
verify_url = "https://%s/recaptcha/api/verify" % VERIFY_SERVER
else:
verify_url = "http://%s/recaptcha/api/verify" % VERIFY_SERVER
# do not add data to Request instead pass it separately to urlopen()
data = params.encode('utf-8')
request = urllib.request.Request(verify_url)
request.add_header("Content-type","application/x-www-form-urlencoded")
request.add_header("User-agent", "reCAPTCHA Python")
httpresp = urllib.request.urlopen(request, data)Despite of solving the problem I still do not know why the code generated by 2to3.py did not work. According to the documentation it should have worked.
发布于 2014-02-15 19:26:25
您猜对了,您需要对数据进行编码,而不是以您的方式进行编码。
正如@Sheena在这就是答案中所写的,您需要两个步骤来编码您的数据:
data = urllib.parse.urlencode(values)
binary_data = data.encode('utf-8')
req = urllib.request.Request(url, binary_data)也不要再给url打电话了。
https://stackoverflow.com/questions/21795976
复制相似问题