django - Python-3 请求参数编码错误

标签 django python-3.x captcha

我一直在开发一个基于 Python 3django 项目。我正在尝试合并验证码。我选择django-recaptcha但不幸的是,该软件包不适用于 python3。于是尝试针对python3进行定制。我做了一些 2to3 的事情,并根据需要做了一些更改。除了请求的 url 编码之外,一切似乎都工作正常。

以下代码片段产生 POST 数据应该是字节或字节的可迭代对象。它不能是 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 中对 url 和其他内容进行编码 -

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 异常。

有人知道怎么解决吗?如有任何帮助,我们将不胜感激:)。

最佳答案

好吧,我自己回答这个问题:P。

python's official documentation 的示例中获取提示,我从 Request 中排除了 data,并将 request 和 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)

尽管解决了问题,但我仍然不知道为什么 2to3.py 生成的代码不起作用。根据文档,它应该有效。

关于django - Python-3 请求参数编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795976/

相关文章:

python - 找出两个 csv 文件之间的差异并标记 em

python - 使用 matplotlib plt.show() 看不到图

Python类继承——Base被子类修改

javascript - 使用Javascript自动点击 Electron 中的验证码框

forms - 让残疾人士可以访问验证码。您使用了哪些方法?

python - Django 'AsgiRequest' 对象没有属性 'content_type'

python - Django 可选参数未从 url 读取

python - Django 中的持久 TCP 连接

python - 从类型提示中获取原始 Python 类型

recaptcha - Google reCAPTCHA 是进行双因素身份验证的工具吗?