python-asyncioaiohttp

I am not getting data at server side request.post()


I am new at Aiohttp and here is a client code for populating data. Below a server code for recieving data. But at server end I am getting KeyError. Also see print(len(request.post()) @ server is 0. But this server code works with Postman testing. And this client code works well with "/httpbin/post/" request. What is wrong with this code. helps appreciated very much.

AT CLIENT SIDE

BASE_URL = "http://127.0.0.1:9001/"
headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
        }
data = {'username': 'achama', 'password': 'password'}

register_endpoint = "register"


jar = aiohttp.CookieJar(unsafe=True)

async def main():
    async with aiohttp.ClientSession(json_serialize=ujson.dumps, cookie_jar=jar) as session:
        async with session.post(url=BASE_URL+register_endpoint, json=data, headers=headers) as resp:
            resp_data = await resp.json(content_type=None)
            print(resp_data)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# Zero-sleep to allow underlying connections to close
loop.run_until_complete(asyncio.sleep(0))
loop.close()

AT SERVER

async def register(self, request): print(len(await request.post()))

posted_data = await request.post()
user_id = await db.get_user_id(self.mongo.loginhub, 
posted_data['username'])
if user_id is None:
    hashed_password = generate_password_hash(posted_data['password'])
        await self.mongo.loginhub.insert_one(
            {'username': posted_data['username'],
             'current_password': hashed_password, 
             'last_password': ""})
        unique_id = await db.get_user_id(self.mongo.loginhub, posted_data['username'])
        await self.mongo.users.insert_one(
            {'unique_id': unique_id, 'username': posted_data['username'], 
            "joined_date": datetime.utcnow(), "active": False})
        return json_response({"message": f"Your account created with {posted_data['username']} Please login to use."})
    else:
        return json_response({"Error": f"Username {posted_data['username']} already exists. Please choose another one."})

SERVER SIDE ERROR

File "/home/bijuknarayan/workspace/aio/marryapp/backend/auth.py", line 44, in register user_id = await db.get_user_id(self.mongo.loginhub, posted_data['username']) File "multidict/_multidict.pyx", line 62, in multidict._multidict._Base.getitem File "multidict/_multidict.pyx", line 57, in multidict._multidict._Base._getone File "multidict/_multidict.pyx", line 52, in multidict._multidict._Base._getone KeyError: 'username'


Solution

  • Replace await request.post() with await request.json() on the server side if you want to handle JSON data.