python请求使用“idna”编解码器编码失败(UnicodeError:标签为空或太长)

2024-10-01 07:49:01 发布

您现在位置:Python中文网/ 问答频道 /正文

[![在此处输入图像说明][1]][1]我在requests包中使用的api调用突然返回以下错误: “UnicodeError:使用'idna'编解码器编码失败(UnicodeError:标签为空或太长)”

我不知道怎么解决这个问题。我的代码如下所示,其中某些凭据是伪造的:

api_key= '123abc'
password = '12345' #password that only idiots use on their luggage
shop_name = 'myshopname'
shop_url = 'https://%s:%s@%s.myecommercesite.com/admin/customers/1234567.json' %(api_key, password, shop_name)

a = requests.get(shop_url)

当我打印shop_url并将其粘贴到我的浏览器中时,我得到的是json格式的返回数据。但是当我运行这个请求时,我得到了idna编解码器错误。在

这曾经是没有问题的工作,但某些地方显然发生了变化,我不确定这是与电子商务网站或请求或是什么原因造成的。在

是否有人遇到过这种类型的错误或知道如何修复它?在

如果我打印url,它看起来像: https://123abc:12345@myshopname.myecommercesite.com/admin/customers/1234567.json

编辑2: 忘记在我的代码示例中包含%(api密钥、密码、商店名称) 编辑: 下面的整个错误消息:

^{pr2}$

Tags: key代码namehttpsapijsonurl错误
1条回答
网友
1楼 · 发布于 2024-10-01 07:49:01

似乎这是来自socket模块的问题。当URL超过64个字符时失败。这仍然是一个悬而未决的问题https://bugs.python.org/issue32958

The error can be consistently reproduced when the first substring of the url hostname is greater than 64 characters long, as in "0123456789012345678901234567890123456789012345678901234567890123.example.com". This wouldn't be a problem, except that it doesn't seem to separate out credentials from the first substring of the hostname so the entire "[user]:[secret]@XXX" section must be less than 65 characters long. This is problematic for services that use longer API keys and expect their submission over basic auth.

当您想使用shopfify API时,有一个替代解决方案: 在base64中对{api_key}:{password}进行编码,并将此值发送到您的请求头中,即{'Authorization': 'Basic {token_base_64}'}

请找到下面的例子,它对我有用。在

    import base64
    import requests

    (...)

    auth = "[API KEY]:[PASSWORD]"

    headers = {
        'Authorization': 'Basic {token}'.format(
            token=base64.b64encode(auth.encode()).decode('ascii'))
    }

    response = requests.get(
        url="https://[YOUR SHOP].myshopify.com/admin/[ENDPOINT]", 
        headers=headers
    )

相关问题 更多 >