我需要以非常慢的 API 下载许多不同的用户数据,因此我决定发出并行请求。在尝试多线程和多进程之后,我认为异步下载在我的情况下是最好的,并且我的代码适用于我在没有包含承载身份验证的标头的情况下尝试过的某些情况...但在这种情况下,它给出了 ClientConnectorCertificateError...任何想法我做错了什么?
import aiohttp
import asyncio
import time
start_time = time.time()
headers = {'accept': 'application/json','Authorization': "Bearer {}".format(token)}
async def get_cch(session, url):
async with session.get(url, headers=headers) as resp:
cch = await resp.json()
x= cch['data']['contractId']
return open(f'{x}.json', 'w').write(json.dumps(cch))
async def main():
async with aiohttp.ClientSession(headers=headers) as session:
tasks = []
for contract in range(len(file_name_list)):
start_date = '2018-01-01'
end_date = '2018-01-05'
url = 'https://apinergia.somenergia.coop/cch/'+file_name_list[contract]+'?tariff=None&type=tg_cchfact&from_='+start_date+'&to_='+end_date+'&limit=30000'
tasks.append(asyncio.ensure_future(get_cch(session, url)))
original_cch = await asyncio.gather(*tasks)
for cch in original_cch:
print(cch)
await main()
print("--- %s seconds ---" % (time.time() - start_time))
传递不记名令牌就像在 aiohttp 中传递任何其他标头一样,使用请求的
headers
参数。与 aiohttp.BasicAuth
的情况不同,没有特殊的方法/语法可以执行此操作。在这种情况下,通过将 "Authorization": "Bearer <API_KEY>"
对添加到标题字典中,您可以正确执行此操作。
您遇到的错误很可能与您传递令牌的方式无关。
这样的东西应该有效:
class BearerAuth(aiohttp.BasicAuth):
def __init__(self, token: str):
self.token = token
def encode(self) -> str:
return f'Bearer: {self.token}'