aiocoap
aiocoap copied to clipboard
Compatibility with flask
Hello Chris,
i am still working on my app to monitor an IoT environment through CoaP and i get rid iff the django server. I am working now with Angular6+ Flask + python3.6 to build a restFul web application. The issue is when i trigger the coap request from my client through Flask i have an error caused by by an incompatibility between asyncio and flask. I've tried to modify my function to get rid off asyncio but I have issues such as :
Failed to fetch resource: 'generator' object has no attribute 'request'
but obviously it's not working so my question is do you think it's possible to request the aiocoap server without using asyncio ?
aiocoap is fundamentally based on asyncio. If you want to use it together with libraries that are not asyncio based themselves, you have two options:
- Modify that library to use asyncio. (For flask, an attempt has been made as flask-asyncio, but that appears to have failed).
- Run asyncio and the thread-using part next to each other in separate threads or even processes (you already had a good-looking model of that with multiprocessing).
You can't simply patch the asyncio out of aiocoap; that would be a completely different library with a different API.
yeah i was guessing that i was opportunist enough to ask you ahah
And, as I should also have mentioned: I recommend you do neither, but simply use a web framework that supports asyncio. I can't recommend one as I have not used any myself, but the asyncio overview page suggests sanic or aiohttp.web
thanks i will take a look !
BTW the Tornado framework is very mature and has a first class support of asyncio and coroutines. Definately worth to give it a try.
If this issue is only about to run asyncio functions in synchronous manner, you can use asyncio.get_event_loop().run_until_complete(my_async_function)
, but you have to pay attention from which thread you are calling this function, eventually you will need to wrap it in asyncio.run_coroutine_threadsafe(...)
as described here.
@aellwein thank you i will give it a try !
@aellwein i've succeeded by calling a synchronous function which calls the async function inside.
@vnahmias nice it works! Just as i said, be careful about calling the asyncio from a Flask request handler. As Flask (possibly) processes requests in WSGI, i.e. one-per-thread, you may run into concurrency issues. In this case, call asyncio functions using run_coroutine_threadsafe().
thanks for the tip !
you are welcome.
Not sure if anyone mentioned this already: Quart https://gitlab.com/pgjones/quart
Very close to Flask, but asyncio in its core. And it even provides the very same plugins. In my opinion, it is the successor of it.