Use Node.js and Socket.io to extend Django's real-time processing capabilities _python

Source: Internet
Author: User
Tags auth extend redis install django node server pip install django install redis redis server

Today, our goal is to use Django,redis, and Socket.io to build a real-time chat room. Although almost all Web applications can build a chat room. This article will tell you at a high level how to convert a rest-based application into a live Web application. I would use Django to create rest parts and actually be free to use any of your comfortable language/frames. Next, let's jump into the code and enumerate the parts we need first.

Composition

    • Django 1.4+
    • Redis 2.6.x (version optional, but recommended)
    • Redis-py 2.7.x (only if you need to use Redis)
    • Node.js v0.8.x
    • Socket.io v0.9.x
    • Cookie v0.0.5
    • Database, SQLite, anything you think is similar to database form


Your version may be different from mine, I have not tested the other version for the time being, all use the latest stable version. If you can't install it in the following way, I have compiled the Ubuntu package. You can get another version of the operating system from the comments.

#https://docs.djangoproject.com/en/dev/topics/install/
sudo apt-get install python-pip
sudo pip install Django
 
#http://redis.io/download
sudo apt-get install redis-server
 
#https://github.com/andymccurdy/ Redis-py
sudo pip install redis  
   
#https://github.com/joyent/node/wiki/ Installing-node.js-via-package-manager
sudo apt-get install python-software-properties
sudo Add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install Nodejs
 
#https:// Github.com/learnboost/socket.io
npm Install Socket.io
 
#https://github.com/shtylman/node-cookie
NPM Install Cookies

Let's start with Django project

django-admin.py startproject realtime_tutorial && cd realtime_tutorial
python manage.py core
mkdir Nodejs

After executing the code, Django Project is configured and the next step is to set up the database in the settings file. Create a blank database first. (This is an example of a settings file.) Add a "core" to my app and configure the templates and URLs path. You can change the configuration information in the settings at will, but it should correspond to your app.

Model

Models is simple, we're going to build a table that contains user and text. If you want to make him more complex, you can add information such as chatroom. (For simplicity's sake, there are only two written here.)

From django.db import models from
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 are going to use, and then execute the following SYNCDB code (the first line of code) to create the database. Then create a few user to test. (second line of code)

Python manage.py syncdb
python manage.py createsuperuser
 
Node Server with Socket.io

This section will introduce the transmission and acquisition of real-time information. Using Node.js to create an app server that relies on Socket.io, use Redis to do this chore. In the Nodejs dictionary, create a file called "Chat.js," 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 (' cookie ');
 
var querystring = require (' querystring ');
var Redis = require (' Socket.io/node_modules/redis ');

 
var sub = redis.createclient ();

 
Subscribe to chat channel sub.subscribe (' Chat '); Configure Socket.io to store the Django Settings cookie io.configure (function () {io.set (' authorization ', function (data, accept) {if (data.he
      Aders.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) {//Send information from Redis to client sub.on (' message ', function (channel, message) {
  Socket.send (message);
   
  }); The client sends messages via Socket.io 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 messages var req = http.get (options, function (res) {res.setencoding (' utf8 '); Output error message Res.on (' Data ', function (messages) {if (Message!= ' Everything worked:) ') {console.log (' Mes
        Sage: ' + message ';
    }
      });
     
    });
    Req.write (values);
  Req.end ();
});

 });
First, we import and create an HTTP server to listen for localhost 4000 ports. Then subscribe to the Redis "chat" Chanel. Finally, it's OK if we call it in Django view.


Last time we set up the Django setting where Socket.io can use cookies in the local domain, which allows us to access cookie data via Socket.handshake.cookie. How to get the user's session.

After we set up Socket.io cookies we can hold a lot of 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 all the site's clients.

Another event is when the client sends a message via Socket.io, we use a string query (QueryString) module to create a query to be sent to our Django service. Our Django service will run on local Port 3000 but you can change that requirement. The path is set to/node_api that URL we will soon create next to Django. Once we send querystring we wait for Django to save the relevant components and return "Everything worked (all working)". Shut down the node console if we don't get the output error returned to us


a node about not using Redis

You really don't need to use Redis for this project, I find it will be a good learning experience if you want to shunt Redis you can create a channel, use expressions or some other class library, where the code will receive a message from Django when a comment is saved, Then you can add annotations to all clients via Socket.io.
Templates

This is where all of our HTML and JavaScript are placed, which allows us to display annotations and interact with our node services

<! DOCTYPE html> 

Our Django shows that we will load a "comments" variable in the next step, so we set and iterate through all the loops below. This part is only used when the page is initially loaded, and our JavaScript will add data to this directory as a new data from our node service

View

Open realtime_tutorial/core/views.py, and edit as I do:

From core.models import Comments, User from django.shortcuts import render from django.http import HttpResponse, Httpre Sponseservererror from DJANGO.VIEWS.DECORATORS.CSRF import csrf_exempt from django.contrib.sessions.models Import Session from Django.contrib.auth.decorators Import login_required import Redis @login_required def Home (request): Co mments = Comments.objects.select_related (). All () [0:100] return render (Request, ' index.html ', Locals ()) @csrf_exempt de F Node_api (Request): Try: #通过sessionid获得 user session = Session.objects.get (session_key=request.
 
    Post.get (' SessionID ')) user_id = session.get_decoded (). Get (' _auth_user_id ') user = User.objects.get (id=user_id) #创建Comment Comments.objects.create (User=user, Text=request. Post.get (' comment ')) #创建后就把它发送到聊天室 r = Redis. Strictredis (host= ' localhost ', port=6379, db=0) r.publish (' chat ', User.username + ': ' + request. Post.get (' comment ')) return HttpResponse ("Everything worked:) ") except Exception, E:return httpresponseservererror (str (e))
 

Let's see what's going on here. Home is a standard view file. Use select_related to get each comment username, instead of returning a comment query collection when the page is first loaded.

The second is the view that our node app sends messages. We get the SessionID from the post and then decode the UserID. Once you have determined that the user exists, you can create the comment. Now, username and comment are sent to Redis server. Finally, send the data to the channel called "Chat".

URLs

This is easier because we're going to use Django's own views and template.

From Django.conf.urls import patterns, include, url
 
urlpatterns = Patterns (',
  url (r ' ^$ ', ' core.views.home ', Name= ' home '),
  url (r ' ^node_api$ ', ' Core.views.node_api ', name= ' Node_api '),
  url (r ' ^login/$ ', ' Django.contrib.auth.views.login ', {' template_name ': ' admin/login.html '}, name= ' login '),
  url (r ' ^logout/$ ', ' Django.contrib.auth.views.logout ', {' next_page ': '/'}, Name= ' logout '),

Start It up!

Open servers.

Python manage.py runserver localhost:3000
 
#In A new Terminal tab CD into the Nodejs directory we created earlier
n Ode Chat.js

I put the code on the GitHub. If you want to do it better, allow user to create and join the chat room. You can also use PHP or rails to develop.

If you have any questions, please write down or contact me in the comments.

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.