I'm new to Django, but the application that I have in mind might end up having URLs that look like this:
http://mysite/compare/id_1/id_2
Where "id_1" and "id_2" are identifiers of two distinct Model objects. In the handler for "compare" I'd like to asynchronously, and in parallel, query and retrieve objects id_1 and id_2.
Is there any way to do this using a standard Django syntax? I'm hoping for pseudocode that ends up looking something like this:
import django.async # Issue the model query, but set it up asynchronously. # The next 2 lines don't actually touch my database o1 = Object(id=id_1).async_fetch() o2 = Object(id=id_2).async_fetch() # Now that I know what I want to query, fire off a fetch to do them all # in parallel, and wait for all queries to finish before proceeding. async.Execute((o2,o2)) # Now the code can use data from o1 and o2 below...
Django has support for writing asynchronous (“async”) views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with performance penalties, and without the ability to have efficient long-running requests.
Latest version of the popular Python web framework also provides an asynchronous interface for all data access operations. Django 4.1, a new version of the major Python-based web framework, adds capabilities such as asynchronous handlers and an ORM interface but also makes some backward-incompatible changes.
To answer directly: No. It's sync.
Django itself is synchronous. each HTTP request will be handled completely synchronously. However you have extensions like django-channels ( https://github.com/django/channels ) , which are asynchronous and are intended for web sockets / etc.
There aren't strictly asynchronous operations as you've described, but I think you can achieve the same effect by using django's in_bulk query operator, which takes a list of ids to query.
Something like this for the urls.py
:
urlpatterns = patterns('', (r'^compare/(\d+)/(\d+)/$', 'my.compareview'), )
And this for the view:
def compareview(request, id1, id2): # in_bulk returns a dict: { obj_id1: <MyModel instance>, # obj_id2: <MyModel instance> } # the SQL pulls all at once, rather than sequentially... arguably # better than async as it pulls in one DB hit, rather than two # happening at the same time comparables = MyModel.objects.in_bulk([id1, id2]) o1, o2 = (comparables.get(id1), comparables.get(id2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With