V
V
Vampre2020-06-29 07:36:33
Python
Vampre, 2020-06-29 07:36:33

Is it mandatory to use async functions with asyncio?

I understand asyncio and aiohttp and noticed that asynchronous wrappers are used everywhere, for example aiohttp_jinja2, aiopg.sa, etc. The question is, is it possible to use the usual synchronous options in aiohttp, for example, the same alchemy? Or if I want to write for example serializers for models, like in django-rest-framework, is it necessary to make them asynchronous too? In general, how appropriate is the usual synchronous code in projects with asyncio and aiohttp?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Pankov, 2020-06-29
@trapwalker

All this asynchrony is for the sole purpose of not waiting while other processes are running.
If you can do without asynchronous code and are not bothered by blocking while accessing the database, then why do you need asyncio and aiohttp at all? Then use flask and run gunicorn many of the same processes with your application and work in them synchronously.
If you make a blocking call to the database in asynchronous code and wait until it answers, then you kill everything useful that asynchronous gives you, but leave all the inconveniences, because asynchronous code is more complicated than synchronous, it’s harder to write, harder to debug, harder test, harder to read.

D
Dr. Bacon, 2020-06-29
@bacon

A call to a synchronous code blocks the event loop and if such calls are "heavy" on the CPU Bound, then your asynchronous code will turn into a regular synchronous single-threaded code, well, plus a small overhead that will be added asyncio
Threat synchronous code without blocking can be run in run_in_executor, but there is nuances.

S
Sergey Tikhonov, 2020-06-30
@tumbler

I used synchronous Django-ORM in conjunction with aiohttp client in a JIRA + Redmine sync task. The idea is that postgres is located on the same server, but the JIRA and Redmine APIs are not only far away, but they also take a very long time to respond. As a result, there is an overhead for synchronous work with the database, but the speed of development and the clarity of the transactional model in such code more than cover it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question