Use Node. js and Socket. IO to extend Django's real-time processing functions

Source: Internet
Author: User
Tags set socket django server install django node server pip install django install redis
This article mainly introduces the use of Node. js and Socket. i/O extends Django's real-time processing function. asynchronous real-time processing is quite powerful. the example in this article is to create a real-time chat room. if you need it, refer to the following example, our goal is to use Django, Redis, and Socket. IO creates a real-time chat room. Although almost all Web applications can create a chat room. This article tells you how to convert a REST-based application into a real-time Web application at a high level. I will use Django to create the REST part. In fact, it is free to use any comfortable language/framework. Next, let's jump into the code and list what we need first.

Composition:

  • Django 1.4 +
  • Redis 2.6.x (optional, but recommended)
  • Redis-py 2.7.x (only required when you use Redis)
  • Node. js v0.8.x
  • Socket. IO v0.9.x
  • Cookie v0.0.5
  • Databases, sqlite, and others that you think are similar to databases


Your version may be different from mine. I have not tested other versions yet, and all of them use the latest stable version. If you cannot install it using the following method, I have compiled the Ubuntu software package. You can get other operating system versions from the comments.

#https://docs.djangoproject.com/en/dev/topics/install/sudo apt-get install python-pipsudo pip install django #http://redis.io/downloadsudo apt-get install redis-server #https://github.com/andymccurdy/redis-pysudo pip install redis     #https://github.com/joyent/node/wiki/Installing-Node.js-via-package-managersudo apt-get install python-software-propertiessudo add-apt-repository ppa:chris-lea/node.jssudo apt-get updatesudo apt-get install nodejs #https://github.com/LearnBoost/socket.ionpm install socket.io #https://github.com/shtylman/node-cookienpm install cookie

Let's start with Django Project

django-admin.py startproject realtime_tutorial && cd realtime_tutorialpython manage.py startapp coremkdir nodejs

After the preceding code is executed, the django project is configured. The next step is to set the database in the settings file. Create a blank database first. (This is an example of setting file. Add a "core" in my app and configure the templates and urls paths. You can modify the configuration information in settings at will, but it must correspond to your app.

Model

Models is simple. we will create a table containing user and text. If you want to make it more complex, you can add information such as chatroom. (For the sake of simplicity, only two are written here)

from django.db import modelsfrom django.contrib.auth.models import User class Comments(models.Model):  user = models.ForeignKey(User)  text = models.CharField(max_length=255)

This is the model we will use. next we will execute the following syncdb code (the first line of code) to create a database. Then create several users for testing. (Line 2 code)

python manage.py syncdbpython manage.py createsuperuser Node Server With Socket.IO

This section describes how to send and obtain real-time information. Use Node. js to create an app server that depends on Socket. IO, and use Redis for this task. Create a file named "chat. js" in the nodejs dictionary and put it here:

Var http = require ('http'); var server = http. createServer (). listen (4000); var io = require ('socket. io '). listen (server); var cookie_reader = require ('cooker'); var querystring = require ('querystring'); var redis = require ('socket. io/node_modules/redis '); var sub = redis. createClient (); // subscribe to chat channelsub. subscribe ('chat'); // Configure socket. io to store cookieio set by Django. configure (function () {io. set ('authorization ', Function (data, accept) {if (data. headers. cookie) {data. cookie = cookie_reader.parse (data. headers. cookie); return accept (null, true);} return accept ('error', false);}); io. set ('log level', 1) ;}); io. sockets. on ('connection', function (socket) {// sends information from Redis to the client sub. on ('message', function (channel, message) {socket. send (message) ;}); // the client uses socket. io sends the message socket. on ('send _ message', function (message) {Values = querystring. stringify ({comment: message, sessionid: socket. handshake. cookie ['sessionid'],}); var options = {host: 'localhost', port: 3000, path: '/node_api', method: 'post', headers: {'content-type': 'application/x-www-form-urlencoded', 'Content-length': values. length }}; // use Django server to send a message var req = http. get (options, function (res) {res. setEncoding ('utf8'); // output error message res. on ('data', Function (message) {if (message! = 'Everything worked :) ') {console. log ('Message: '+ Message) ;}}) ;}); req. write (values); req. end ();});});

First, import and create an http server to listen to Port localhost 4000. Then subscribe to Redis's "chat" chanel. Finally, we only need to call it in Django view.


Last time we set the Django setting where Socket. IO can use cookies in the local field, which allows us to access cookie data through socket. handshake. cookie. How can we get the user's session.

We set Socket. i/O cookies can only be held after many events. The first event is the Redis release channel. when our users notice that a new message has been notified that it will send a message to clients on all sites.

Another event is that when the client sends a message through Socket. IO, we use the string query module to create a query to be sent to our Django service. Our Django service will run on the local port 3000, but you can change that requirement. Set the path to the/node_api URL. we will soon create it next to Django. Once queryString is sent, Django will save the relevant components and return "Everything worked (all working)" to us )". If no output error is returned to us, close the node console.


A node that does not use Redis

You really don't have to use Redis for this project. I found it will be a good learning experience. if you want to divert Redis, you can create a channel, use expressions or some other class libraries, the code above will receive a message from Django. when a comment is saved, you can use Socket. add comments to all clients for IO
Template

This is where all our HTML and javascript are placed. it allows us to display comments and interact with our Node Service.

 Realtime Django 
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.