Server-Sent Push Notification on Google App Engine using TaskQueues for Background Processing Long Running Tasks
This is the source code you need in your Google App Engine Python solution for notifying the user when using Google App Engine task/background taskqueue has completed a step in the TaskQueue processing steps and also when the TaskQueue has been totally completed. But wait! You want to only send the notification to the Specific User who initiated the TaskQueue request.
Step 1 - How can I publish a message to client XYZ only?
This is easy and Here is the source code:
Also to secure your app, make sure you get proper keys via: https://admin.pubnub.com dashboard.
JavaScript
<script src=https://pubnub.a.ssl.fastly.net/pubnub-3.4.3.min.js></script>
<script>(function(){
var pubnub = PUBNUB.init({ subscribe_key : 'demo', ssl : true });
pubnub.subscribe({
channel : '0IHM4b2VpamZhaWU0eThyaWpvaWdma3Mg', // SESSION ID
message : function(message) { alert(message) } // ALERT MESSAGE
});
})();</script>
Note that we are using a simple JavaScript Alert() function for showing the message, however you will instead want to turn that into a more robust
<div>{message-here}</div>
notification area on your page.
TaskQueue Setup
taskqueue.add(
url='/my-long-task',
countdown=1,
method='GET',
params={ 'sessionid' : '0IHM4b2VpamZhaWU0eThyaWpvaWdma3Mg' }
)
Basically you are using the User Session ID to route the communication to user XYZ. Now in Google App Engine Python, you will publish using the Session ID any message state you want to the client.
Google App Engine - Python Task
import webapp2
from Pubnub import Pubnub ## Download - https://raw.github.com/pubnub/pubnub-api/master/google-app-engine/python/Pubnub.py
pubnub = Pubnub( "demo", "demo" )
def server_to_client_notify( sessionId, message ):
pubnub.publish({
"channel" : sessionId, ## SESSION ID
"message" : "hi!"
})
class LongRunningTaskQueue(webapp2.RequestHandler):
def get(self):
## GET Session ID
sessionId = urllib.unquote(self.request.get( 'sessionid', '' ))
server_to_client_notify( sessionId, "Starting Your Job" )
## - DO A LOT OF WORK - ##
## - DO A LOT OF WORK - ##
## - DO A LOT OF WORK - ##
server_to_client_notify( sessionId, "Your Job is Nearly Complete" )
## - DO A LOT OF WORK - ##
## - DO A LOT OF WORK - ##
## - DO A LOT OF WORK - ##
server_to_client_notify( sessionId, "Your Job has Finished!" )
app = webapp2.WSGIApplication([('/my-long-task', LongRunningTaskQueue)])
The basic concept is that you Post the SESSION ID along with the TaskQueue URL command which starts/adds the task into the Queue. Then when the TaskQueue starts, you can grab the URL params.
In case you were wondering if there will be more than 1 step, the answer is: "There is only one step."