Channel API (Server to client communication)

Original web design allowed only one-way client-server communication. But there are some cases in which server need to communicate with browser.

One way is to communicate from client to server after a fixed interval that is polling mechanism. But this is not the effective way even it is costly method to hit server again and again.

Google provides Channel API to do the same.

Channel API creates a connection between your application and Google servers, allowing your application to send messages to JavaScript clients in real time without the use of polling.

This is useful for applications designed to update users about new information immediately. Some example use-cases include multi-player games, or chat rooms.

Key Components : Channel API

 

  • JavaScript client that connects to the channel  using the channel’s unique token generated on the server.
  • Socket/Channel is created between server and client and listens on this channel

 

2) Server :-
  • Creats a unique channel and send to each JavaScript client so they can connect and listen to their channel.
  • Send data/messages to clients via their channels.

3) Client Id :-

  • Identifies individual JavaScript clients on the server.
  • Server sends a particular message to particular client using the client ID.

 

4) Tokens :-
  • Allowing the JavaScript client to connect and listen to the channel created for it.
  • The server creates one token for each client using information such as the client’s Client ID and expiration time.
  • Tokens expire after two hours and should also be treated as secret.

 

5) The channel
  • A channel is a one-way communication path through which the server sends updates to a specific JavaScript client identified by its Client ID.
  • The server receives updates from clients via HTTP requests, then sends the messages to relevant clients via their channels.

 

The message/data :-
  • Messages are sent via HTTP requests from one client to the server.
  • When a message is received, the server passes the message to the designated client via the correct channel identified by the client ID.
  • Messages are limited to 32K.

 

Socket
  • The JavaScript client opens a socket using the token provided by the server. It uses the socket to listen for updates on the channel.

 

Presence
  • The server can register to receive a notification when a client connects to or disconnects from a channel.

 

For more information

 

Code Example :

 

Python (Server Side)
 
1) Import channel api
 

       from google.appengine.api import channel

2) Create channel bassed on some parameter 

userId = user_id
channelId = channel.create_channel(userId)


JavaScript (Client Side)

1) Inculde Channel.js to project


<script type=“text/javascript” src=“https://talkgadget.google.com/talkgadget/channel.js”></script>


2) Get channel based on channelId created on server side

   
    var  channel = new goog.appengine.Channel(channelId);
 
3) Open channel

    var socket = channel.open();
 
4) Attach methods to sockets

       socket.onopen = function () {
           console.log(“Channel Opened.”);
       };
       socket.onmessage = function (responseData) {
         alert(‘Server Messge : ‘ + responseData.data);

       };
       socket.onerror = function () {
           console.log(‘Channel Error’);
       };
       socket.onclose = function () {
           console.log(‘Channel Close’);
       };
   };


5) Done

 

How to get xhtml2pdf working on Google App Engine
  1. Create folder named pdf into App Engine project folder.

 

  1. Copy xhtml2pdf, html5lib, reportlab folder to pdf folder.

 

  1. Copy six.py file to pdf folder.

 

  1. Create PDFHandler.py that will create the pdf file and make it to download.

 

Explanation of PDFHandler.py

1) Import webapp2

 

import webapp2
2) Import vendor to add installed lib to work

 

     from google.appengine.ext import vendor
     vendor.add(‘pdf’)
3) Import files that are required to create pdf file
     
     from xhtml2pdf import pisa
     from cStringIO import StringIO

 

4) Class that will handle the action
    
      class DownloadPDF:
         def post(self):
             try:
                content = StringIO(“<table><tr><th>Name</th></tr><tr><td>Sunil</td></tr></table>”)
                output = StringIO()
                pdf = pisa.CreatePDF(content, output, encoding = ’utf-8’)
    pdf_data = pdf.dest.getvalue()
 except ValueError:
    logging.info(‘Error’)
 
5) Set the response header to make this downloadable as pdf

 

        self.response.headers[‘Content-Type‘] = ‘application/pdf’
        self.response.headers[‘Content-Disposition’] = ‘attachment;filename=Any_Name’

 

6) Write pdf data as response

 

       self.response.write(pdf_data)

 

7) Define app variable to make URL working

 

       app = webapp2.WSGIApplication([(‘/downloadpdf‘, DownloadPDF)], debug=True)

 

8) Entry in app.yaml to run PDFHandler.py

 

     – url: /reports/downloadpdf
        script: PDFHandler.app

 

Clubbing it together :
 
import webapp2
     from google.appengine.ext import vendor
     vendor.add(‘pdf’)
     from xhtml2pdf import pisa
     from cStringIO import StringIO
      
      class DownloadPDF:
         def post(self):
             try:
                content = StringIO(“<table><tr><th>Name</th></tr><tr><td>Sunil</td></tr></table>”)
                output = StringIO()
                pdf = pisa.CreatePDF(content, output, encoding = ’utf-8’)
    pdf_data = pdf.dest.getvalue()
              
                self.response.headers[‘Content-Type‘] = ‘application/pdf’
                self.response.headers[‘Content-Disposition’] = ‘attachment;filename=Any_Name’
                self.response.write(pdf_data)
 except ValueError:
    logging.info(‘Error’)

 

        app = webapp2.WSGIApplication([(‘/downloadpdf‘, DownloadPDF)], debug=True)
 
 
Download from github :

 

 
Rollback : Undo the previous deployment that failed to complete in Google App Engine[Python]
When we deploy project on Google App Engine and due to some error it got cancelled. It may happen if user manually cancel the deployment of project in between or due to slow network or any other reason. This leads to incomplete deployment of projects and revoke deploy from the next time as the existing deployment is in progress. Rollback is the option to undo the previous deployment that failed to complete but marked as in progress deployment.
There are two ways to solve this using rollback option of appcfg.py command.

Solution 1:-

1) Set environment variable for python

2) Place your project’s app.yaml in 

C:\Program Files(x86)\Google\google_appengine

3) Open cmd and using change the directory to 

cd C:\Program Files (x86)\Google\google_appengine

4) Run the command

python appcfg.py rollback app.yaml

5) Remove the app.yaml file from that folder after rollback as the this command uses app.yaml information when you upload the app.

Solution 2:-

Use the following command :-

appcfg.py rollback “<directory>”

Further Reading

http://array151.com/blog/appcfg-one-click-deployment-to-google-app-engine/

http://array151.com/blog/appcfg-download-source-code-and-logs-from-gae/

http://array151.com/blog/how-to-get-xhtml2pdf-working-on-google-app-engine/

http://array151.com/blog/channel-api-server-to-client-communication/

Netbeans Plugin : Install python in netbeans

No direct plugin is available that can be installed from netbeans marketplace itself. To support python in netbeans, you need to download plugin files manually and install it.

Steps :-

1) Open NetBeans and click  “Tools” -> “Plugins”.
2) Click the “Downloaded” .
3) Click the “Add Plugins…” button.

4) Browse to the folder you unzipped the Python plugin files to.

5) Select all *.nbm” files.

6) Click “Open” and Click “Install”.

7) Restart your browser.

8) Done

en_USEnglish
en_USEnglish