Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are asynchronous Django model queries possible?

Tags:

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... 
like image 352
slacy Avatar asked May 27 '09 22:05

slacy


People also ask

Is Django good for asynchronous?

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.

Is Django 4 asynchronous?

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.

Are Django signals asynchronous?

To answer directly: No. It's sync.

Is Django synchronous?

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.


1 Answers

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))       
like image 167
Jarret Hardie Avatar answered Sep 21 '22 17:09

Jarret Hardie