python - 设置 `aiohttp.ClientSession` 默认参数
问题描述
我正在从 迁移requests
到aiohttp
,并且我以前使用过requests.Session.params
,为会话发出的每个请求设置默认查询参数。
我如何正确实现与 的等价物aiohttp.ClientSession
?
我试过了:
- 子类
aiohttp.ClientSession
化以覆盖该_request
方法。不过,这引发了一个DepcrecationWarning: Inheritance from ClientSession is discouraged
。 - 子类
aiohttp.ClientResponse
化以覆盖该__init__
方法,并在params
那里更新,然后将子类传递给aiohttp.ClientSession
. 那是行不通的,因为我需要在会话的基础上定义(并且是可变的)自定义参数。
编辑:为了澄清,我希望我的代码看起来如何的示例:
from aiohttp import ClientSession
session = ClientSession()
# Do something fancy here, or in the initialization of `ClientSession`, so that
# `default_params` is set as the default parameters for each request
default_params = dict(some_parameter="a value")
async with session.get("http://httpbin.org/get") as resp:
j = await resp.json()
assert j["args"] == default_params
# Do something fancy here, where we change the default parameters
default_params.update(some_parameter="another value")
async with session.get("http://httpbin.org/get") as resp:
j = await resp.json()
assert j["args"] == default_params
解决方案
自定义请求标头
如果您需要将 HTTP 标头添加到请求中,请将它们在 dict 中传递给 headers 参数。
它在文档http://docs.aiohttp.org/en/stable/client_advanced.html#custom-request-headers
url = 'http://example.com/image'
payload = b'GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00'
b'\x00\x00\x01\x00\x01\x00\x00\x02\x00;'
headers = {'content-type': 'image/gif'}
await session.post(url,
data=payload,
headers=headers)
要添加默认和以后的自定义参数,您可以这样做而不进行任何子类化(基于文档的这一部分)
import asyncio
from aiohttp import ClientSession
async def fetch(url, params, loop):
async with ClientSession() as session:
async with session.get(url, params=params) as response:
print(response.request_info)
print(str(response.url))
print(response.status)
args = await response.json()
resp_text = await response.text()
print('args:', args['args'])
print(resp_text)
def main(url, params):
loop = asyncio.get_event_loop()
return loop.run_until_complete(fetch(url, params, loop))
if __name__ == '__main__':
url = 'http://httpbin.org/get'
default_params = {'param1': 1, 'param2': 2}
main(url, default_params)
new_params = {'some_parameter': 'a value', 'other_parameter': 'another value'}
default_params.update(new_params)
main(url, default_params)
结果:
RequestInfo(url=URL('http://httpbin.org/get?param1=1¶m2=2'), method='GET', headers=<CIMultiDict('Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'Python/3.5 aiohttp/3.4.4')>, real_url=URL('http://httpbin.org/get?param1=1¶m2=2'))
http://httpbin.org/get?param1=1¶m2=2
200
args: {'param1': '1', 'param2': '2'}
{
"args": {
"param1": "1",
"param2": "2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Python/3.5 aiohttp/3.4.4"
},
"origin": "10.10.10.10",
"url": "http://httpbin.org/get?param1=1¶m2=2"
}
RequestInfo(url=URL('http://httpbin.org/get?param1=1¶m2=2&some_parameter=a+value&other_parameter=another+value'), method='GET', headers=<CIMultiDict('Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'Python/3.5 aiohttp/3.4.4')>, real_url=URL('http://httpbin.org/get?param1=1¶m2=2&some_parameter=a+value&other_parameter=another+value'))
http://httpbin.org/get?param1=1¶m2=2&some_parameter=a+value&other_parameter=another+value
200
args: {'other_parameter': 'another value', 'param1': '1', 'param2': '2', 'some_parameter': 'a value'}
{
"args": {
"other_parameter": "another value",
"param1": "1",
"param2": "2",
"some_parameter": "a value"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Python/3.5 aiohttp/3.4.4"
},
"origin": "10.10.10.10",
"url": "http://httpbin.org/get?param1=1¶m2=2&some_parameter=a+value&other_parameter=another+value"
}
推荐阅读
- excel - 在 Excel 中用顺序数据填充大量行
- xamarin - 如何确保 iOS 正确挂起 Xamarin Forms 应用程序(AVAudioSessionCategoryPlayback 模式)以防止电池耗尽?
- c++ - 如何创建一个以数字范围为键的 unordered_map | C++
- r - 如何使用 Rmpfr::mpfr 减少计算时间?
- excel - 使用查找/替换编辑 Word 标题
- bash - 使用 sudoers 来限制 www-data 的脚本文件?(nohup)
- unix - 在 UNIX 中替换文件末尾的十六进制分隔符和额外字符
- javascript - Esri JS Api 4.18 需要 node_models 的 ncp 副本以用于 BUILD 和 START。我需要复制资产以在 storybook.js 中工作吗?
- angular - Angular向构造函数添加服务导致没有内容显示
- jwt - 为什么 Quarkus JWT 在每个端点上都未经授权返回