【问题标题】:python HTTP Client - proxy requests as a GET parameterpython HTTP客户端-代理请求作为GET参数
【发布时间】:2018-03-06 17:31:05
【问题描述】:

我在防火墙后面,需要以http://the-proxy-gateway.set?url=https%3A%2F%2Fapi.stripe.com 的格式执行所有请求。

所以我需要将所需的 URL 作为 GET 参数传递(并对请求进行 uri 编码)。

如何配置标准 Python http 客户端(请求、urllib2 或其他)来执行此操作?

【问题讨论】:

标签: python proxy python-requests


【解决方案1】:

我可能会遗漏一些东西,但这看起来就像一个普通的 request.getparams 设置。

这个例子在代理 url 是假的意义上不起作用,但是如果您查看错误消息(为简洁而修改),参数似乎被正确编码。

In[2]: import requests
  ...:
  ...: PROXY_URL = 'http://the-proxy-gateway.set'
  ...:
  ...:
  ...: def proxy_as_get(url):
  ...:     r = requests.get(PROXY_URL, params={'url': url})
  ...:     r.raise_for_status()
  ...:     return r.json()  # ???
  ...:
In[3]: r = proxy_as_get('https://api.stripe.com')
Traceback (most recent call last):
    ...
    Max retries exceeded with
    *****
    url: /?url=https%3A%2F%2Fapi.stripe.com
    *****
    ...

另一个例子:

In[2]: import requests
In[3]: PROXY_URL = 'http://the-proxy-gateway.set'
In[4]: params = {'url': 'https://api.stripe.com'}
In[5]: req = requests.Request('GET', PROXY_URL, params=params)
In[6]: prepped = req.prepare()
In[7]: prepped.url
Out[7]: 'http://the-proxy-gateway.set/?url=https%3A%2F%2Fapi.stripe.com'

【讨论】:

  • 感谢您的回复,这是通过网关执行每个请求的手动方式。但是,我需要设置 http 客户端(在这种情况下为请求)以始终使用这种方法。原因是 Stripe Python 也使用 requests 客户端,我需要它来代理。
  • @JørgenSvendsen 您是否尝试过设置HTTP_PROXY 和/或HTTPS_PROXY 环境变量as shown in the docs?另外,Stripe Python 似乎也有代理设置,have you tried setting that?如果这些不起作用,那么您可以使用上面的此功能对requests.get 进行猴子补丁。
猜你喜欢
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多