Nodjango, websockets with Django and Nodejs
Patrick Paul
- Audience level:
- Intermediate
- Category:
- Web Frameworks
Description
Nodjango, a portmanteau of Node and Django, is a simple module to add websockets to Django. Rather than complicatedly rolling a Django websockets server in Python, this library simply connects to a Nodejs socket.io server as a client, and exposes certain Python services like the Django ORM over this websocket to the Nodejs application. A proxy routes non-websockets traffic to the Django webserver.
Abstract
**Nodjango**, a portmanteau of _Node_ and _Django_, is a simple library to add websockets to Django. Rather than complicatedly rolling a Django websockets server in Python, this library simply connects to a Nodejs socket.io server as a client, and exposes certain Python services like the Django ORM over this websocket. There are a lot of rich resources for developing single-page applications across the gulf in the Javascript ecosystem, and I sought (and developed) a simple way to develop Nodejs/Angular/socket.io applications using the same Django framework modules I've come to love: GeoDjango ORM, tastypie RESTful API resources, South migrations, etc.
### Sample stack
- *Django* WSGI service listens for requests on port `8000`
- *Nodejs* listens on both ports `80` and `3044` for socket.io connections
- *Nodejs* listens on port 80 to proxy requests matching `/` to `127.0.0.1:8000`
- **New** *Django* socket.io client connects to `127.0.0.1:3044` and listens for ORM requests from the *Nodejs* application (server *or client* !)
### Danger zone
By connecting Django to socket.io, it becomes possible to do crazy not-yet-secure things in client-side javascript like so:
<script type="text/javascript">
socket.emit('django_orm', {
callback: 'django_orm_response',
app: 'my_application',
model: 'my_model',
method: 'get',
kwargs: {
'id': 1
}
});
socket.on('django_orm_response', function(payload){
jQuery('#username').val(payload.username);
});
</script>
### Next steps
I have the MVP working where I manually configure this stack and daemonize the various processes.
Ultimately, I want to package the entire Nodejs proxy, websockets, `npm`, and other dependencies into a Python package that can be installed into any virtualenv (using [virtual-node](https://github.com/elbaschid/virtual-node). Then, overload the `python manage.py runserver` command to possibly start this complete stack with the front-matter proxy listening on `80` or `8000` as expected, with socket.io. Then, with only `pip install nodjango` and adding the app your Django project's settings you can start writing client-side javascript that interacts with the Django ORM.