如何在请求中指定等效于 `--proxy-headers` curl 参数? [英] How does one specify the equivalent of `--proxy-headers` curl argument into requests?

查看:48
本文介绍了如何在请求中指定等效于 `--proxy-headers` curl 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在使用请求时只将一些标头传递到我的代理中,但我没有看到这样做的方法.

I'm looking to pass some headers only into my proxies as I'm using requests, and I don't see a method to do it.

urllib3.ProxyManager 有一个 proxy_headers 参数,所以我假设有一种方法可以为请求库设置它 - 我错过了什么吗?

the urllib3.ProxyManager has a proxy_headers parameter, so I would assume there's a way to set it for the requests library - am I missing something?

推荐答案

您可以使用自定义的 HTTPAdapter 来实现(例如如下所示):

You can do it with a customized HTTPAdapter (for example like the following):

import requests

proxyheaders = { 'http://proxy.that.needs.header:8080/': { 'ProxyHeader1': 'SomeValue', 'ProxyHeaderN': 'OtherValue' } }

class ProxyHeaderAwareHTTPAdapter(requests.adapters.HTTPAdapter):
    def proxy_headers(self, proxy):
        if proxy in proxyheaders:
            return proxyheaders[proxy]
        else:
            return None

s = requests.Session()
s.mount('http://', ProxyHeaderAwareHTTPAdapter())
s.mount('https://', ProxyHeaderAwareHTTPAdapter())
s.get(....)
...

如果你喜欢的话,你也可以直接创建并返回一个配置好的 urllib3.ProxyManager 如果你覆盖了 proxy_manager_for 方法而不是 proxy_headers.
https://requests.kennethreitz.org/en/master/api/#requests.adapters.HTTPAdapter

You could also directly create and return a configured urllib3.ProxyManager if You overwrite the proxy_manager_for methos instead of proxy_headers if You like.
https://requests.kennethreitz.org/en/master/api/#requests.adapters.HTTPAdapter

这篇关于如何在请求中指定等效于 `--proxy-headers` curl 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆