Python 3请求或urllib-如何始终添加头?
标题说明了一切:是否有一种“最好”的方法总是向每个请求添加标题?我有一个内部工具,希望将请求ID发送到其他内部工具;我在寻找一个幸运的解决方案。我浏览了两者的文档,似乎这不是一个受欢迎的要求,因为我找不到烹饪书的例子 我正在考虑几个解决方案:Python 3请求或urllib-如何始终添加头?,python,python-requests,urllib,Python,Python Requests,Urllib,标题说明了一切:是否有一种“最好”的方法总是向每个请求添加标题?我有一个内部工具,希望将请求ID发送到其他内部工具;我在寻找一个幸运的解决方案。我浏览了两者的文档,似乎这不是一个受欢迎的要求,因为我找不到烹饪书的例子 我正在考虑几个解决方案: 在我自己的瘦包装中包装请求并使用它。需要教导代码开发人员记住不要导入请求,而要导入myrequestswrapper as requests 猴子补丁请求。我不喜欢猴子打补丁,但也许就这一次。。。?我害怕在需要不向这个特定系统发送头的时候 编辑:为什么我不
导入请求
,而要导入myrequestswrapper as requests
会话子类化:
In [64]: from requests.adapters import HTTPAdapter
In [65]: from requests.cookies import cookiejar_from_dict
In [66]: class CookieMonsterSession(Session):
...:
...: def __init__(self, *args, **kwgs):
...: super(CookieMonsterSession, self).__init__(*args, **kwgs)
...: # Override default adapters with 0-pooling adapters
...: self.mount('https://', HTTPAdapter(pool_connections=1,
...: pool_maxsize=0))
...: self.mount('http://', HTTPAdapter(pool_connections=1,
...: pool_maxsize=0))
...: @property
...: def cookies(self):
...: """ Freshly baked cookies, always!"""
...: return cookiejar_from_dict({})
...: @cookies.setter
...: def cookies(self, newcookies):
...: """ OM NOM NOM NOM..."""
...: pass
...:
In [67]: s = CookieMonsterSession()
In [69]: real_s = Session()
In [70]: s.get('http://www.google.fi')
Out[70]: <Response [200]>
In [71]: s.cookies
Out[71]: <RequestsCookieJar[]>
In [72]: real_s.get('http://www.google.fi')
Out[72]: <Response [200]>
In [73]: real_s.cookies
Out[73]: <RequestsCookieJar[Cookie(version=0, name='NID', value='86=14qy...Rurx', port=None, port_specified=False, domain='.google.fi', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1489744358, discard=False, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>
在行动中:
In [1]: import customrequests as requests
In [2]: print(requests.get('http://httpbin.org/headers').text)
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1"
}
}
In [3]: requests.custom_headers['X-Test'] = "I'm always here"
In [4]: print(requests.get('http://httpbin.org/headers').text)
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1",
"X-Test": "I'm always here"
}
}
想了想,但是:它存储我不想要的cookies,还保持连接打开,这在应用的整个生命周期中可能会有问题。如果这些都是问题,我建议按照你最初的包装想法。在查看代码时,如果添加的内容正在使用或未使用,这一点是显而易见的。
# customrequests.py
from functools import wraps
from requests import api as requests_api
custom_headers = {}
def _header_wrapper(f):
@wraps(f)
def wrapper(*args, **kwgs):
headers = kwgs.pop('headers', None) or {}
headers.update(custom_headers)
return f(*args, headers=headers, **kwgs)
return wrapper
request = _header_wrapper(requests_api.request)
get = _header_wrapper(requests_api.get)
options = _header_wrapper(requests_api.options)
head = _header_wrapper(requests_api.head)
post = _header_wrapper(requests_api.post)
put = _header_wrapper(requests_api.put)
patch = _header_wrapper(requests_api.patch)
delete = _header_wrapper(requests_api.delete)
In [1]: import customrequests as requests
In [2]: print(requests.get('http://httpbin.org/headers').text)
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1"
}
}
In [3]: requests.custom_headers['X-Test'] = "I'm always here"
In [4]: print(requests.get('http://httpbin.org/headers').text)
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.11.1",
"X-Test": "I'm always here"
}
}