简体   繁体   English

如何将 Python 中的请求 GET 请求转换为具有有效负载的异步?

[英]How to convert a requests GET request in Python to asyncio with payloads?

I am trying to parallelize requests to the Wikidata API using Python's asyncio module.我正在尝试使用 Python 的 asyncio 模块并行化对维基数据 API 的请求。

My current synchronous script does the following:我当前的同步脚本执行以下操作:

import requests

base_url = "https://www.wikidata.org/w/api.php&"
payload = {
        "action": "query",
        "list": "search",
        "srsearch": search_term,
        "language": "en",
        "format": "json",
        "origin": "*",
    }
res = requests.get(base_url, params=payload)

I am trying to do the same using asyncio , to send requests asynchronously.我正在尝试使用asyncio做同样的事情,异步发送请求。

From this blogpost and the documentation, I understood that I need something like:这篇博文和文档中,我了解到我需要这样的东西:

from aiohttp import ClientSession

async with ClientSession() as session:
        async with session.get(url) as response:
            response = await response.read()

However, I did not manage to find how to add these payloads in the request.但是,我没有设法找到如何在请求中添加这些有效负载。 Do I have to reconstruct the URL manually or is there a way to send the payloads in asyncio?我必须手动重建 URL 还是有办法在 asyncio 中发送有效载荷?

Try the following code试试下面的代码

async with ClientSession() as session:
        async with session.get(url, params=payload) as response:
            response = await response.read()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM