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

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'

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

Related

My function does not execute when using await in a async function pyscript

I try to fetch data from my api in python using pyscript. Following the pyscript documentation I use the async keyword on my main function and use asyncio.ensure_future to execute it, everything before the first await work but not the await keyword and any other line of code after it.
This is my code:
async def request(url: str,
method: str = "GET",
body: Optional[str] = None,
headers: Optional[dict[str, str]] = None,
**fetch_kwargs: Any) -> FetchResponse:
kwargs = {
"method": method,
"mode": "no-cors"
} # CORS: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
if body and method not in ["GET", "HEAD"]:
kwargs["body"] = body
if headers:
kwargs["headers"] = headers
kwargs.update(fetch_kwargs)
response = await pyfetch(url, **kwargs)
return response
async def get_barycenter(
filename: str,
base_url: str = "http://localhost:8001") -> dict[str, Any] | None:
headers = {"Content-type": "application/json"}
response = await request(f"{base_url}/barycenter/?image_name={filename}",
headers=headers)
body = await response.json()
if body.status != 200:
return None
return body.msg
async def main():
print('start')
test = await get_barycenter("img.jpg")
print(test)
print("end")
asyncio.ensure_future(main())
The result is only the print of start and nothing else no print of test are even "end".
I tested the API the data is visible in Insomnia and I set up correctly the cors Policy.
Part of the issue here is an existing issue in PyScript where exceptions raised in Coroutines aren't displayed on the page. To help with this for now, I would recommend adding the following snippet before your request function:
import js
def handler(loop, context):
js.console.error(context.message)
raise(context.exception)
pyscript.loop.set_exception_handler(handler)
This way, exceptions raised in coroutines are displayed in the browser's console log.
What the root issue of the the fetch request is I couldn't say, but at least this will get errors displaying and help you troubleshoot. For example, when I run your code, I see:
GET http://localhost:8001/barycenter/?image_name=img.jpg net::ERR_CONNECTION_REFUSED
Since I don't have a local server running - hopefully the errors that appear for you are more helpful.

Adding user object to scope django-channels

I am trying to add websockets to my app. I use JWT tokens so I have to overide middleware for it.
#database_sync_to_async
def get_user(token):
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=ALGORITHM)
except:
return AnonymousUser()
token_exp = datetime.fromtimestamp(payload['exp'])
if token_exp < datetime.utcnow():
return AnonymousUser()
try:
response = requests.get(settings.OAUTH_URL, headers={'Authorization': f"Bearer {token}"})
if response.status_code == 200:
user = response.json()
return user
except:
error_logger.exception("Server is not available!")
class TokenAuthMiddleware(BaseMiddleware):
async def __call__(self, scope, receive, send):
close_old_connections()
try:
token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None)
except ValueError:
token_key = None
scope['user'] = await get_user(token_key)
return await super().__call__(scope, receive, send)
def JwtAuthMiddlewareStack(inner):
return TokenAuthMiddleware(AuthMiddlewareStack(inner))
My service is a microservice so the User model is located in another service. So I have to send a request to the service where the instance model is located. When I try to add "user" dict-like object to scope it returns me an error:
helpdesk_web | File "/usr/local/lib/python3.10/site-packages/channels/auth.py", line 176, in resolve_scope
helpdesk_web | scope["user"]._wrapped = await get_user(scope)
helpdesk_web | AttributeError: 'dict' object has no attribute '_wrapped'
If I delete this line scope['user'] = await get_user(token_key) or pass to the function model instance everything works.
Is there a way to add 'users' dict-like object instead of model instance to scope?

Downloading File in Parallelwith Asyncio

I trying to pull Avro files from an API link while using Asyncio. Currently it just returns nothing if the link is to an avro file - while all my other API calls which pull json data work. What am I missing?
credentials = {'authorization': XXXXX}
async def get_data(link, session,creds)-> None:
async with session.get(url, url=link, headers=credential) as res:
content = await res.read()
r = await session.request('GET', url=str(link), headers=creds)
data = await r
return
async def data_distributor_function(credential)-> None:
async with aiohttp.ClientSession() as session:
link_list = ["https://.....","https://.....","https://.....","https://.....","https://....."]
tasks = []
for link in link_list:
tasks.append(wait_for(get_data( link=link, session=session,creds=credential),timeout=10))
results = await asyncio.gather(*tasks, return_exceptions=True)
return
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
data = asyncio.run(data_distributor_function(credential),debug=True)
If I don't do the API call in asyncio, I can just use a standard request and it works (it's just slow).
reply = requests.request("GET", link, credentials)

Python Socket.io event handling

I'm a complete beginner when it comes to socket, so please bear with me if the question seems too trivial for you.
The following is a code that i found on GitLab and I'm trying to understand
import os
import logging
import uuid
import socketio
from aiohttp import web
import sys
sys.path.append('.')
logging.basicConfig(level=logging.WARN,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')
# Home page
async def index(request):
index_file = open('examples/rasa_demo/templates/index.html')
return web.Response(body=index_file.read().encode('utf-8'), headers={'content-type': 'text/html'})
# Action endpoint
async def webhook(request):
"""Webhook to retrieve action calls."""
action_call = await request.json()
try:
response = await executor.run(action_call)
except ActionExecutionRejection as e:
logger.error(str(e))
response = {"error": str(e), "action_name": e.action_name}
response.status_code = 400
return response
return web.json_response(response)
# Web app routing
app = web.Application()
app.add_routes([
web.get('/', index),
web.post('/webhook', webhook),
web.static('/static', 'examples/rasa_demo/static')
])
# Instantiate all bot agents
bots = BotFactory.createAll()
# Websocket through SocketIO with support for regular HTTP endpoints
sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*')
sio.attach(app)
#sio.on('session_request')
async def on_session_request(sid, data):
if data is None:
data = {}
if 'session_id' not in data or data['session_id'] is None:
data['session_id'] = uuid.uuid4().hex
await sio.emit('session_confirm', data['session_id'])
#sio.on('user_uttered')
async def on_user_uttered(sid, message):
custom_data = message.get('customData', {})
lang = custom_data.get('lang', 'en')
user_message = message.get('message', '')
bot_responses = await bots[lang].handle_text(user_message) #await BotFactory.getOrCreate(lang).handle_text(user_message)
for bot_response in bot_responses:
json = __parse_bot_response(bot_response)
await sio.emit('bot_uttered', json, room=sid)
What I'm trying to understand is how do the event handlers catch or events like 'session_request' or'user_uttered' when they were never emitted.
Thank you.

websocket handshake fails with django channels

EDIT: correction after #Ken4scholars comment below
I have the following consumer which fails right after connecting
consumers.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer
#...
class ListGeneratedTokensByFileConsumer(AsyncJsonWebsocketConsumer):
stop = False
async def websocket_connect(self,event):
await self.accept()
self.stop = False
async def websocket_receive(self,event):
await self.send_json({"text":"received","accept": True})
await self.send_tokens_list()
async def websocket_disconnect(self,event):
self.stop = True
async def send_tokens_list(self):
some_path = "..."
while self.stop == False:
await asyncio.sleep(2)
the_message = {}
if os.path.isfile("some_file.json")):
with open(os.path.join(some_path ,"some_file.json"),'r') as new_tok:
the_message = json.load(new_tok)
if not the_message:
print("waiting...")
else:
await self.send_json(the_message)
await self.close()
It always throws the error: ERR_CONNECTION:RESEST and the websocket disconnects with code 1006. This might seem familiar to recent changes in django-channels but since I am sending a text once the websocket opens and send a message back from the consumer it should do the trick. Or is there something wrong?
routing.py
url(r'^myapp/sub_path/(?P<pk>\d+)/sub_sub_path/',ListGeneratedTokensByFileConsumer)
and the websocket endpoint in js is:
.js
var loc = window.location;
var wsStart = "ws://";
if (loc.protocol == "https:") {
wsStart = "wss://";
}
var endpoint = wsStart + loc.host + loc.pathname + "sub_sub_path" + "/";
for info, with channels-redis==2.3.2, channels==2.3.0, asgiref==3.2.2, daphne==2.3.0, django==2.0.8
If you see something like in django logs:
WebSocket HANDSHAKING /ws/your_route
WebSocket REJECT /ws/your_route
WebSocket DISCONNECT /ws/your_route
And you wrapped websocket router with AllowedHostsOriginValidator in the asgi.py like:
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(
URLRouter(
chat_websocket_urlpatterns
))
})
Then you definetely should check the ALLOWED_HOSTS variable in the settings.py, maybe you forgot to put something in there. In my case it was just because I didn't specify my IP address, only localhost.
This is most likely not that the asker looked for, but I thought it may come handy to someone else, as there is not much info about the django channels in this site.

Resources