python headers中有冒号的参数

注意:python 版本 3.10.9

在使用 request.get(url, headers =header)方法时候,  由于请求头中有冒号的参数:

:authority  :method  :path  :scheme

运行py文件就直接报错:

valueError: Invalid header name b':authority'

 

搜到的方法有两种,hyper 和  httpx

hyper

pip 安装之后,运行直接报错,

ImportError: cannot import name ‘Iterable’ from 'collections'

 

需要改为   from collections.abc import Iterable

 Iterable以及以下collections的方法都在3.10版本后被取消了。

["Awaitable", "Coroutine", "AsyncIterable", "AsyncIterator", "AsyncGenerator", "Hashable", "Iterable", "Iterator", "Generator", "Reversible", "Sized", "Container", "Callable", "Collection", "Set", "MutableSet", "Mapping", "MutableMapping", "MappingView", "KeysView", "ItemsView", "ValuesView", "Sequence", "MutableSequence", "ByteString"]

示例代码:

# 修改之前的出错代码行
# from collections import Iterable

# 修改为以下
try:
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable

 

修改之后运行,继续报错。 依照刚才的方法都一 一改过来。

有4个文件需要修改:根据下图错误提示的py文件,一一找到并修改from 。。。import

我这边修改过来,依然会报错冒号不支持。最后放弃了。

httpx

关键代码:

http_client = httpx.Client(http2=True, timeout=5)
response = http_client.get(url, headers = header)

在header上折腾了好久,加上 :authority  :method  :path  :scheme 这几个参数后,一直报错

httpx.LocalProtocolError: Received duplicate pseudo-header field b':authority'

不加:authority ,请求url就出错(其实是没问题的,应该还是代码哪里错了)

看错误提示很明显,有重复的请求头。

然后看了下httpx的请求代码:http2.py

def _send_request_headers(self, request: Request, stream_id: int) -> None:
        ......

        authority = [v for k, v in request.headers if k.lower() == b"host"][0]

        headers = [
            (b":method", request.method),
            (b":authority", authority),
            (b":scheme", request.url.scheme),
            (b":path", request.url.target),
        ] + [
            (k.lower(), v)
            for k, v in request.headers
            if k.lower()
            not in (
                b"host",
                b"transfer-encoding",
            )
        ]

这个方法会自动加上 这4个请求头,所以代码中伪装header的时候,不需要再加了。 

折腾了好久,终于搞定了。 祝大家的bug也早日解决。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wwwarewow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值