我正在从 requests
迁移到 aiohttp
,并且我之前使用过 requests.Session.params
来设置默认查询参数对于 session 中发出的每个请求。
如何正确实现与 aiohttp.ClientSession
相同的效果?
我已经尝试过:
- 子类化
aiohttp.ClientSession
以覆盖_request
方法。 但这会引发DepcrecationWarning:不鼓励从 ClientSession 继承
。 - 子类化
aiohttp.ClientResponse
以覆盖__init__
方法,并更新其中的params
,然后将子类传递给aiohttp .ClientSession
。 这是行不通的,因为我需要在 session 的基础上定义自定义参数(并且是可变的)。
编辑:我希望代码的外观示例,以供澄清:
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
最佳答案
Custom Request Headers
If you need to add HTTP headers to a request, pass them in a dict to the headers parameter.
它在文档 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)
要添加默认参数和稍后的自定义参数,您可以这样做,而无需进行任何子类化( based on this part of documentation )
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"
}
关于python - 设置 `aiohttp.ClientSession` 默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563238/