32

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

Igor Lavrynenko
  • 171
  • 2
  • 13
nskalis
  • 2,232
  • 8
  • 30
  • 49

3 Answers3

42

ahh the data part is accessed like that

await request.json()

You can find this in official aiohttp docs

wolendranh
  • 4,202
  • 1
  • 28
  • 37
nskalis
  • 2,232
  • 8
  • 30
  • 49
  • 1
    await is the key here and the co-routine has to be a async/await request. But aiohttp library supports synchronous also. This confuses the developers in this regard. I hope, aiohttp-server module supports only async/await methods in order to retrieve the posted content from the HTTP Body. Kindly correct me if there is any way of rendering the Posted Content. – Vikash Jun 20 '19 at 14:37
9

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()
user2788368
  • 91
  • 1
  • 2
4

you can access POST request body data using

if request.body_exists:
        print(await request.read())