Reputation: 2382
Could you please advise on the following?
On the localhost:8900
there is aiohttp server running
When I do a request like (using the python2 module requests) from python
requests.get("http://127.0.01:8900/api/bgp/show-route",
data={'topo':"switzerland",
'pop':"zrh",
'prefix':"1.1.1.1/32"})
And there is a route defined in the aiohttp server
app.router.add_route("GET", "/api/bgp/show-route", api_bgp_show_route)
which is being handled like
def api_bgp_show_route(request):
pass
The question is: how do I retrieve on server-side the data part of the request? meaning {'topo':"switzerland", 'pop':"zrh", 'prefix':"1.1.1.1/32"}
Upvotes: 34
Views: 45265
Reputation: 11
If you want to use aiohttp, two main components are missing from your code. First, you need to create an aiohttp session with session = aiohttp.ClientSession()
. Secondly, you need to be in an asynchronous function to use session.get()
and await the function.
You can call it with your function as follows: response = await session.get(url)
put this in a function starting with async before def when declaring it for instance as follow:
async def test(url: str) -> None:
session = aiohttp.ClientSession()
response = await session.get(url)
Finally to launch an asynchronous function use asyncio.run() as follow: asyncio.run(test(url: str))
If you just want to print the result, use print(response)
.If you want the response as a Python object you can parse the result from json with: data = await response.json()
This is a very concise answer, if you want a more step-by-step detail guide, I have written one on how to use aiohttp at: https://medium.com/@thomas.vidori/d9863b3ae7c2
Upvotes: 0
Reputation: 111
It depends on the format you want the data to be.
To get a string:
request.text()
To get bytes:
request.read()
To get a JSON dict (Attention, throws a json.decoder.JSONDecodeError if the data is malformatted!):
request.json()
Upvotes: 11
Reputation: 81
you can access POST request body data using
if request.body_exists:
print(await request.read())
Upvotes: 6
Reputation: 2382
ahh the data
part is accessed like that
await request.json()
You can find this in official aiohttp docs
Upvotes: 43