Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aiohttp: how-to retrieve the data (body) in aiohttp server from requests.get

Tags:

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"}

like image 317
nskalis Avatar asked Sep 12 '16 11:09

nskalis


People also ask

Is aiohttp better than requests?

get is that requests fetches the whole body of the response at once and remembers it, but aiohttp doesn't. aiohttp lets you ignore the body, or read it in chunks, or read it after looking at the headers/status code. That's why you need to do a second await : aiohttp needs to do more I/O to get the response body.

What does aiohttp ClientSession do?

By default the aiohttp. ClientSession object will hold a connector with a maximum of 100 connections, putting the rest in a queue. This is quite a big number, this means you must be connected to a hundred different servers (not pages!) concurrently before even having to consider if your task needs resource adjustment.

How do I pass headers in aiohttp?

If you need to add HTTP headers to a request, pass them in a dict to the headers parameter. await session. post(url, data='Привет, Мир! ')


2 Answers

ahh the data part is accessed like that

await request.json() 

You can find this in official aiohttp docs

like image 153
nskalis Avatar answered Oct 18 '22 00:10

nskalis


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() 
like image 42
user2788368 Avatar answered Oct 17 '22 23:10

user2788368