Python-3请求参数编码错误 [英] Python-3 Request parameter encoding error
问题描述
我一直在基于 Python 3
进行 django
项目。我正在尝试合并验证码
。我选择了 django-recaptcha ,但不幸的是,该软件包不适用于python3。因此尝试为python3量身定制。我做了一些 2to3
的工作,并根据需要进行了一些更改。除了 Request的url编码
以外,其他所有内容似乎都正常运行。
I have been working on a django
project based upon Python 3
. I am trying to incorporate captcha
. I choosed django-recaptcha but unfortunately the package is not available for python3. So tried to tailor it for python3. I did some 2to3
stuff and made some changes as per need. Everything seems to work fine except the url encoding for Request
.
以下代码段的收益 POST数据应为字节或字节的可迭代数。不能是str类型。
异常。
Following snippet yields POST data should be bytes or an iterable of bytes. It cannot be of type str.
exception.
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
中对网址和其他内容进行编码-
So I tried to encode the url and other stuff in 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错误未知的URL类型:b'http
异常。
有人知道如何解决它吗?感谢您的帮助:)。
Does anyone know how to fix it? Any help is appreciated :).
推荐答案
好的,我会自己回答:P。
Alright I will answer this myself :P.
在 python的官方文档中获取示例提示 ,我从 Request
中排除了 data
,并分别传递了 request和data
到 urlopen()
。以下是更新的代码段-
Taking hints from an example at python's official documentation, I excluded data
from Request
and separately passed request and data
to urlopen()
. Below is the updated snippet -
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)
尽管解决了问题,我仍然不知道为什么他2to3.py生成的代码不起作用。根据文档,它应该可以正常工作。
这篇关于Python-3请求参数编码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!