我是 Aiohttp 的新手,这里是用于填充数据的客户端代码。下面是用于接收数据的服务器代码。但在服务器端我收到 KeyError。另请参阅 print(len(request.post()) @ server is 0。但是此服务器代码适用于 Postman 测试。此客户端代码适用于“/httpbin/post/”请求。此代码有什么问题。帮助非常感谢。
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()
异步定义寄存器(自身,请求): 打印(len(等待请求。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."})
文件“/home/bijuknarayan/workspace/aio/marryapp/backend/auth.py”, 第 44 行,在寄存器中 user_id =等待db.get_user_id(self.mongo.loginhub,posted_data ['用户名'])文件“multidict / _multidict.pyx”,第62行, 在 multidict._multidict._Base.getitem 文件中 “multidict/_multidict.pyx”,第 57 行, multidict._multidict._Base._getone 文件“multidict/_multidict.pyx”, 第 52 行,在 multidict._multidict._Base._getone KeyError: '用户名'
如果要处理 JSON 数据,请将服务器端的
await request.post()
替换为 await request.json()
。
在服务器端使用
await request.json()
而不是 await request.post()
来处理 JSON 数据。