如何将参数和标头传递给 aiohttp ClientSession [英] How to pass params and headers to aiohttp ClientSession
本文介绍了如何将参数和标头传递给 aiohttp ClientSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望将 params
和 headers
传递给 aiohttp.ClientSession
,如图所示这里.
I wish to pass params
and headers
to aiohttp.ClientSession
as shown here.
这是我尝试过的:
async def make_request(self, url, headers, params):
async with aiohttp.ClientSession(headers=headers, params=params) as session:
async with self.limit, session.get(url=url) as response:
await asyncio.sleep(self.rate)
resp = await response.read()
return resp
async def process(url, url_id, update_id, rate, limit):
limit = asyncio.BoundedSemaphore(limit)
f = Fetch(
rate=rate,
limit=limit,
)
if "coinmarketcap" in url:
params = {
'start': '1',
'limit': '1',
'convert': 'USD,BTC'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': API_KEY,
}
else:
params = {}
headers = {}
result = await f.make_request(url, headers, params)
但我收到错误:
Unexpected Argument at:
async with aiohttp.ClientSession(headers=headers, params=params) as session
如果假设 url 是 coinmarketcap,我希望设置标题并且 no params/headers
否则.如何解决?
I wish to set headers if let's say the url was coinmarketcap and no params/headers
otherwise.
How to fix it?
推荐答案
无法将 params 属性传递给会话.您需要在 get 调用中发送它,如下所示:
The params attribute can't be passed to the session. You'll need to send it in the get call, like so:
async def make_request(self, url, headers, params):
async with aiohttp.ClientSession(headers=header) as session:
async with self.limit, session.get(url=url, params=params) as response:
await asyncio.sleep(self.rate)
resp = await response.read()
return resp
您可以在客户端会话初始化或 get 调用中发送标头.我认为两者都可以.
You can send the headers in the client session initialisation or in the get call. I think either will work.
这篇关于如何将参数和标头传递给 aiohttp ClientSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文