SlideShare a Scribd company logo
1 of 24
Download to read offline
Comet web applications with Python,
                 Django & Orbited


@ PyCon Italia Qu4ttro       Massimo Scamarcia
http://www.pycon.it/           http://www.webright.it/




                        
Comet web applications with Python,
        Django & Orbited




How to push real-time data to
      web browsers?



              
Comet web applications with Python,
                  Django & Orbited


AJAX Polling
   Client: sends AJAX request.
   Server:
       Data available: sends response.
       No data: sends empty response.
   Client: sends AJAX request again.




                        
Comet web applications with Python,
              Django & Orbited




Latency, bandwidth, memory usage and scaling issues!


                    
Comet web applications with Python,
         Django & Orbited




      What about Comet?



              
Comet web applications with Python,
                Django & Orbited




Not a technology in itself
 Long Polling, IFRAME stream, HTMLFile, XHR Streaming, HTML5 SSE




                        
Comet web applications with Python,
         Django & Orbited




          It's an hack!
       Still waiting for an unanimous way to do it.




                   
Comet web applications with Python,
                      Django & Orbited


Long Polling
   Client: sends AJAX request.
   Server: holds the request.
              Data available: sends response.
              Timeout reached: empty response.
   Client: sends AJAX request again.




                            
Comet web applications with Python,
                        Django & Orbited

Http Push (HTTP Streaming*)
   Client: sends HTTP request.
   Server: doesn't terminate the connection.
   Server: sends data when available.
   Connection closed:
                Data is queued.
                Client reconnects.

    [*] http://ajaxpatterns.org/HTTP_Streaming



                               
Comet web applications with Python,
                    Django & Orbited
   HTTP Push: better for heavily-loaded apps.
       Not cross-browser.
   Long Polling: cross-browser and easy.
       Bandwidth usage.
       Too many connections.
   Async Python servers* are better for both:
       Twisted, Tornado, Dieselweb, Eventlet, Concurrence,
         Circuits, Gevent, Cogen.

[*] http://nichol.as/asynchronous-servers-in-python


                             
Comet web applications with Python,
         Django & Orbited




      What about Orbited?



              
Comet web applications with Python,
        Django & Orbited




        He's here to solve problems!

                
Comet web applications with Python,
                     Django & Orbited


   Based on Twisted.
   STOMP* (ActiveMQ, RabbitMQ), IRC and XMPP
     protocol support.
   Ready-to-use and cross-browser JavaScript client
     code.
   You don't have to reinvent the wheel!

[*] http://stomp.codehaus.org/



                             
Comet web applications with Python,
           Django & Orbited




Using Django and Orbited
        Example app developed for PyConIt4:
      http://pyconquiz.webright.it/




                   
Comet web applications with Python,
                  Django & Orbited

Django is used for:
   Application logic.
   Template rendering.
   User auth and registration.
   Handling AJAX requests.
   Sending messages to STOMP server.

                             ...Orbited and jQuery do the rest!




                          
Comet web applications with Python,
        Django & Orbited




              
Comet web applications with Python,
                    Django & Orbited

orbited.cfg                    settings.py
 [global]                       # Available using context
 #reactor=select                # processor or templatetag
 #reactor=kqueue
 reactor = epoll                ORBITED_HOST = 'localhost'
 proxy.enabled = 1              ORBITED_PORT = 8080
 session.ping_interval = 300
                                STOMP_HOST = 'localhost'
 [listen]                       STOMP_PORT = 61613
 http://localhost:8080
 stomp://localhost:61613

 [access]
 * -> localhost:61613



                            
Comet web applications with Python,
                  Django & Orbited

Django base template (<head /> tag)
 <script>document.domain = document.domain;</script>
 <script src="{{ ORBITED_MEDIA_URL }}Orbited.js"></script>
 <script type="text/javascript">
 Orbited.settings.port = {{ ORBITED_PORT }};
 Orbited.settings.hostname = "{{ ORBITED_HOST }}";
 Orbited.settings.streaming = true;

 TCPSocket = Orbited.TCPSocket;
 </script>

 <script src="{{ ORBITED_MEDIA_URL }}JSON.js"></script>
 <script
 src="{{ ORBITED_MEDIA_URL }}protocols/stomp/stomp.js"></script>



                          
Comet web applications with Python,
                     Django & Orbited
<script>
$(document).ready(function() {
    stomp = new STOMPClient();
    stomp.onopen = function() { debug('Connected.');};
    stomp.onclose = function(c) { debug(Lost Connection, Code: '+c);};
    stomp.onerror = function(error){ debug("Error: " + error);};
    stomp.onerrorframe = function(frame){ debug("Error: " + frame.body);};
    stomp.onconnectedframe = function() {
        {% if game %}
        stomp.subscribe('/games/{{ game.id }}/status');
        stomp.subscribe('/games/{{ game.id }}/players');
       {% else %}// subscribe to other channels...{% endif %}
    };
    stomp.onmessageframe = function(frame){
        // frame.headers.destination for channel, frame.body for JSON data
        destpatterns.dispatch(frame);
    };
    stomp.connect('{{ STOMP_HOST }}', {{ STOMP_PORT }});
});
</script>
                              
Comet web applications with Python,
                   Django & Orbited

Django view
 @require_POST
 @login_required
 def game_start(request, game_id):
   game = get_object_or_404(Game, id=game_id)
   if request.user != game.author:
      return HttpResponseForbidden()
   try:
       # start() method set game start_time and send JSON
       # to ”/games/{{ game.id }}/status” using stomp.py
      game.start()
   except GameError, e:
       return JSONResponse({'error': str(e)})
   return JSONResponse({})



                           
Comet web applications with Python,
        Django & Orbited




       Does it scale?



              
Comet web applications with Python,
        Django & Orbited




              
Comet web applications with Python,
        Django & Orbited




              
Comet web applications with Python,
         Django & Orbited




           Thank you
       and have fun with the quiz game!




                

More Related Content

What's hot (6)

State of the art: Server-Side JavaScript - dejeuner fulljs
State of the art: Server-Side JavaScript - dejeuner fulljsState of the art: Server-Side JavaScript - dejeuner fulljs
State of the art: Server-Side JavaScript - dejeuner fulljs
 
TorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyTorqueBox - When Java meets Ruby
TorqueBox - When Java meets Ruby
 
Torquebox - O melhor dos dois mundos
Torquebox - O melhor dos dois mundosTorquebox - O melhor dos dois mundos
Torquebox - O melhor dos dois mundos
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsers
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Server
 
NeXTPLAN: Enterprise software that rocks!
NeXTPLAN: Enterprise software that rocks!NeXTPLAN: Enterprise software that rocks!
NeXTPLAN: Enterprise software that rocks!
 

Viewers also liked (6)

SWDC 2010: Programming to Patterns
SWDC 2010: Programming to PatternsSWDC 2010: Programming to Patterns
SWDC 2010: Programming to Patterns
 
ICBA Webinar, 2015 Strategies. Ben Pankonin, Ann Chen
ICBA Webinar, 2015 Strategies. Ben Pankonin, Ann ChenICBA Webinar, 2015 Strategies. Ben Pankonin, Ann Chen
ICBA Webinar, 2015 Strategies. Ben Pankonin, Ann Chen
 
London Ajax User Group Meetup: Comet Panel
London Ajax User Group Meetup: Comet PanelLondon Ajax User Group Meetup: Comet Panel
London Ajax User Group Meetup: Comet Panel
 
College House Computing: ITAs and Our Role
College House Computing: ITAs and Our RoleCollege House Computing: ITAs and Our Role
College House Computing: ITAs and Our Role
 
Communities: Build Or Join
Communities:  Build Or JoinCommunities:  Build Or Join
Communities: Build Or Join
 
zc.buildout: "Un modo estremamente civile per sviluppare un'applicazione"
zc.buildout: "Un modo estremamente civile per sviluppare un'applicazione"zc.buildout: "Un modo estremamente civile per sviluppare un'applicazione"
zc.buildout: "Un modo estremamente civile per sviluppare un'applicazione"
 

Similar to Comet web applications with Python, Django & Orbited

Ring: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureRing: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic Clojure
Mark McGranaghan
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
Rick Copeland
 
Socket applications
Socket applicationsSocket applications
Socket applications
João Moura
 

Similar to Comet web applications with Python, Django & Orbited (20)

Comet web applications with Python, Django & Orbited
Comet web applications with Python, Django & OrbitedComet web applications with Python, Django & Orbited
Comet web applications with Python, Django & Orbited
 
Real time web (Orbited) at BCNE3
Real time web (Orbited) at BCNE3Real time web (Orbited) at BCNE3
Real time web (Orbited) at BCNE3
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Connecting to Web Services on Android
Connecting to Web Services on AndroidConnecting to Web Services on Android
Connecting to Web Services on Android
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
 
Going Live! with Comet
Going Live! with CometGoing Live! with Comet
Going Live! with Comet
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009
 
Ring: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureRing: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic Clojure
 
huhu
huhuhuhu
huhu
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
 
Comet from JavaOne 2008
Comet from JavaOne 2008Comet from JavaOne 2008
Comet from JavaOne 2008
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Framework
 
Djabot – Python Jabber Bot
Djabot – Python Jabber BotDjabot – Python Jabber Bot
Djabot – Python Jabber Bot
 
asyncio community, one year later
asyncio community, one year laterasyncio community, one year later
asyncio community, one year later
 
Socket applications
Socket applicationsSocket applications
Socket applications
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET«Real Time» Web Applications with SignalR in ASP.NET
«Real Time» Web Applications with SignalR in ASP.NET
 
Python, WebRTC and You (v2)
Python, WebRTC and You (v2)Python, WebRTC and You (v2)
Python, WebRTC and You (v2)
 
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and ScalaWriting highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
 

More from PyCon Italia

Feed back report 2010
Feed back report 2010Feed back report 2010
Feed back report 2010
PyCon Italia
 
Python: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi geneticiPython: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi genetici
PyCon Italia
 
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni pythonPyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
PyCon Italia
 
OpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonOpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con Python
PyCon Italia
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
PyCon Italia
 
Monitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopMonitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntop
PyCon Italia
 
Crogioli, alambicchi e beute: dove mettere i vostri dati.
Crogioli, alambicchi e beute: dove mettere i vostri dati.Crogioli, alambicchi e beute: dove mettere i vostri dati.
Crogioli, alambicchi e beute: dove mettere i vostri dati.
PyCon Italia
 

More from PyCon Italia (19)

Feed back report 2010
Feed back report 2010Feed back report 2010
Feed back report 2010
 
Spyppolare o non spyppolare
Spyppolare o non spyppolareSpyppolare o non spyppolare
Spyppolare o non spyppolare
 
Undici anni di lavoro con Python
Undici anni di lavoro con PythonUndici anni di lavoro con Python
Undici anni di lavoro con Python
 
socket e SocketServer: il framework per i server Internet in Python
socket e SocketServer: il framework per i server Internet in Pythonsocket e SocketServer: il framework per i server Internet in Python
socket e SocketServer: il framework per i server Internet in Python
 
Qt mobile PySide bindings
Qt mobile PySide bindingsQt mobile PySide bindings
Qt mobile PySide bindings
 
Python: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi geneticiPython: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi genetici
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Python in the browser
Python in the browserPython in the browser
Python in the browser
 
PyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fast
 
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni pythonPyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
 
OpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonOpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con Python
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
 
Monitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntopMonitoraggio del Traffico di Rete Usando Python ed ntop
Monitoraggio del Traffico di Rete Usando Python ed ntop
 
Jython for embedded software validation
Jython for embedded software validationJython for embedded software validation
Jython for embedded software validation
 
Foxgame introduzione all'apprendimento automatico
Foxgame introduzione all'apprendimento automaticoFoxgame introduzione all'apprendimento automatico
Foxgame introduzione all'apprendimento automatico
 
Effective EC2
Effective EC2Effective EC2
Effective EC2
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
 
Crogioli, alambicchi e beute: dove mettere i vostri dati.
Crogioli, alambicchi e beute: dove mettere i vostri dati.Crogioli, alambicchi e beute: dove mettere i vostri dati.
Crogioli, alambicchi e beute: dove mettere i vostri dati.
 
Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Comet web applications with Python, Django & Orbited

  • 1. Comet web applications with Python, Django & Orbited @ PyCon Italia Qu4ttro Massimo Scamarcia http://www.pycon.it/ http://www.webright.it/    
  • 2. Comet web applications with Python, Django & Orbited How to push real-time data to web browsers?    
  • 3. Comet web applications with Python, Django & Orbited AJAX Polling  Client: sends AJAX request.  Server:  Data available: sends response.  No data: sends empty response.  Client: sends AJAX request again.    
  • 4. Comet web applications with Python, Django & Orbited Latency, bandwidth, memory usage and scaling issues!    
  • 5. Comet web applications with Python, Django & Orbited What about Comet?    
  • 6. Comet web applications with Python, Django & Orbited Not a technology in itself Long Polling, IFRAME stream, HTMLFile, XHR Streaming, HTML5 SSE    
  • 7. Comet web applications with Python, Django & Orbited It's an hack! Still waiting for an unanimous way to do it.    
  • 8. Comet web applications with Python, Django & Orbited Long Polling  Client: sends AJAX request.  Server: holds the request.  Data available: sends response.  Timeout reached: empty response.  Client: sends AJAX request again.    
  • 9. Comet web applications with Python, Django & Orbited Http Push (HTTP Streaming*)  Client: sends HTTP request.  Server: doesn't terminate the connection.  Server: sends data when available.  Connection closed:  Data is queued.  Client reconnects. [*] http://ajaxpatterns.org/HTTP_Streaming    
  • 10. Comet web applications with Python, Django & Orbited  HTTP Push: better for heavily-loaded apps.  Not cross-browser.  Long Polling: cross-browser and easy.  Bandwidth usage.  Too many connections.  Async Python servers* are better for both:  Twisted, Tornado, Dieselweb, Eventlet, Concurrence, Circuits, Gevent, Cogen. [*] http://nichol.as/asynchronous-servers-in-python    
  • 11. Comet web applications with Python, Django & Orbited What about Orbited?    
  • 12. Comet web applications with Python, Django & Orbited He's here to solve problems!    
  • 13. Comet web applications with Python, Django & Orbited  Based on Twisted.  STOMP* (ActiveMQ, RabbitMQ), IRC and XMPP protocol support.  Ready-to-use and cross-browser JavaScript client code.  You don't have to reinvent the wheel! [*] http://stomp.codehaus.org/    
  • 14. Comet web applications with Python, Django & Orbited Using Django and Orbited Example app developed for PyConIt4: http://pyconquiz.webright.it/    
  • 15. Comet web applications with Python, Django & Orbited Django is used for:  Application logic.  Template rendering.  User auth and registration.  Handling AJAX requests.  Sending messages to STOMP server. ...Orbited and jQuery do the rest!    
  • 16. Comet web applications with Python, Django & Orbited    
  • 17. Comet web applications with Python, Django & Orbited orbited.cfg settings.py [global] # Available using context #reactor=select # processor or templatetag #reactor=kqueue reactor = epoll ORBITED_HOST = 'localhost' proxy.enabled = 1 ORBITED_PORT = 8080 session.ping_interval = 300 STOMP_HOST = 'localhost' [listen] STOMP_PORT = 61613 http://localhost:8080 stomp://localhost:61613 [access] * -> localhost:61613    
  • 18. Comet web applications with Python, Django & Orbited Django base template (<head /> tag) <script>document.domain = document.domain;</script> <script src="{{ ORBITED_MEDIA_URL }}Orbited.js"></script> <script type="text/javascript"> Orbited.settings.port = {{ ORBITED_PORT }}; Orbited.settings.hostname = "{{ ORBITED_HOST }}"; Orbited.settings.streaming = true; TCPSocket = Orbited.TCPSocket; </script> <script src="{{ ORBITED_MEDIA_URL }}JSON.js"></script> <script src="{{ ORBITED_MEDIA_URL }}protocols/stomp/stomp.js"></script>    
  • 19. Comet web applications with Python, Django & Orbited <script> $(document).ready(function() { stomp = new STOMPClient(); stomp.onopen = function() { debug('Connected.');}; stomp.onclose = function(c) { debug(Lost Connection, Code: '+c);}; stomp.onerror = function(error){ debug("Error: " + error);}; stomp.onerrorframe = function(frame){ debug("Error: " + frame.body);}; stomp.onconnectedframe = function() { {% if game %} stomp.subscribe('/games/{{ game.id }}/status'); stomp.subscribe('/games/{{ game.id }}/players'); {% else %}// subscribe to other channels...{% endif %} }; stomp.onmessageframe = function(frame){ // frame.headers.destination for channel, frame.body for JSON data destpatterns.dispatch(frame); }; stomp.connect('{{ STOMP_HOST }}', {{ STOMP_PORT }}); }); </script>    
  • 20. Comet web applications with Python, Django & Orbited Django view @require_POST @login_required def game_start(request, game_id): game = get_object_or_404(Game, id=game_id) if request.user != game.author: return HttpResponseForbidden() try: # start() method set game start_time and send JSON # to ”/games/{{ game.id }}/status” using stomp.py game.start() except GameError, e: return JSONResponse({'error': str(e)}) return JSONResponse({})    
  • 21. Comet web applications with Python, Django & Orbited Does it scale?    
  • 22. Comet web applications with Python, Django & Orbited    
  • 23. Comet web applications with Python, Django & Orbited    
  • 24. Comet web applications with Python, Django & Orbited Thank you and have fun with the quiz game!