SlideShare a Scribd company logo
Python in the Browser                                                                             01/06/2010 13:45




                                            Python in the Browser
                     Web Programming with Silverlight & IronPython
 Michael Foord
 michael@voidspace.org.uk
 www.voidspace.org.uk
 @voidspace


         Python in the browser with Silverlight & IronPython

                  Introduction
                  Silverlight
                  Say Hello to Vera
                  Getting Started: One JS File
                  External Python Files
                  How it works
                  Loading the Javascript
                  Loading the Python Runtime
                  The IronPython Payload
                  Running the Python Code
                  So we can write code...
                  Using .NET APIs
                  Silverlight Toolkit
                  Try Python
                  Questions




 Introduction




           You, the Python developer, use Python because you want to, but in the browser you use
           JavaScript because you think you have to. With Silverlight you can write Python code in the

file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                                  Page 1 of 12
Python in the Browser                                                     01/06/2010 13:45



           browser.


 Silverlight
           Microsoft browser plugin
           Now installed in over 50% of browsers (riastats)
           Cross platform: Windows and Mac, plus Linux with Moonlight
           Cross browser: Safari, Firefox, IE and Chrome
           Runs IronPython and IronRuby
           Sockets, threading, local browser storage APIs
           Webcam access, out of browser apps
           IronPython docs at ironpython.net/browser/

 IronPython 2.6 - the equivalent of Python 2.6.

 Silverlight features include:

           A ui system based on WPF
           Full access to the browser DOM
           Calling between Javascript and Silverlight code
           Out of browser applications
           Video, streaming media and 'deep zoom'
           Local browser storage
           Socket and threading APIs (etc)
           Lots more...


 Say Hello to Vera




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html        Page 2 of 12
Python in the Browser                                                                           01/06/2010 13:45




 Over 19000 lines of Python code (plus hundreds of lines of xaml) written over a 7 month period by two
 developers.


 Getting Started: One JS File
 Loading IronPython:

         <script
          src="http://gestalt.ironpython.net/dlr-latest.js"
          type="text/javascript"></script>

 Python in script tags:

         <script type="text/python">
             def onclick(s, e):
                 window.Alert("Hello from Python!")
             document.button.events.onclick += handler
             document.message.innerHTML = 'Hello Python!'
         </script>

 To develop a Python application in the browser, you just need your favorite text editor; so open it up,
 create a HTML file, reference dlr.js, and then you can use script-tags for running Python code.



file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                              Page 3 of 12
Python in the Browser                                                                          01/06/2010 13:45




 External Python Files
         <script type="text/python" src="repl.py"></script>

 This creates a console when you add ?console to the url.




 We can reference Python files as well as inline Python.

 The console is hooked up to sys.stdout, so your existing text-based Python scripts can come alive in the
 browser (sans reading from stdin). Also, any print statements you use in the app will show up in the
 console as well, making it a great println-debugging tool.

 Let's play around with the page a bit, adding a DOM element and changing it's HTML content to
 "Ouch!" when clicked:

 >>> dir(document)
 [..., 'CreateElement', ...]
 >>> div = document.CreateElement("div")
 >>> div.innerHTML = "Hello from Python!"
 >>> document.Body.AppendChild(div)
 >>> div.id = "message"
 >>> div.SetStyleAttribute("font-size", "24px")
 >>> def say_ouch(o, e):
 ... o.innerHTML = "Ouch!"
 ...
 >>> document.message.events.onclick += say_ouch


 How it works



file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 4 of 12
Python in the Browser                                                                            01/06/2010 13:45




 dlr.js contains a collection of functions for creating a Silverlight control on the HTML page that is
 capable of running IronPython code.


 Loading the Javascript




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                                  Page 5 of 12
Python in the Browser                                                                            01/06/2010 13:45




 By default, just running dlr.js injects a Silverlight <object> tag into the page (immediately after the
 script-tag) so it can run only DOM-based scripts, and also scans for other script-tags indicating that you
 want a Silverlight rendering surface, but more on that later.


 Loading the Python Runtime




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                               Page 6 of 12
Python in the Browser                                                                         01/06/2010 13:45




 The injected Silverlight control points to a Silverlight application made specifically to embed the
 dynamic language runtime, the compiler/runtime/embedding infrastructure IronPython is built on, find all
 the Python code the HTML page uses, and executes it.

 The XAP is tiny, as the DLR and IronPython are in separate packages which are downloaded on-
 demand; the DLR and IronPython are not installed with Silverlight, so they must be downloaded with
 the application.


 The IronPython Payload




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                            Page 7 of 12
Python in the Browser                                                                          01/06/2010 13:45




 However, if the application depends on the ironpython.net binaries, the user's browser will cache them
 and they won't be re-downloaded for any other app; almost as good as being part of the installer, while
 still being able to be open-source.


 Running the Python Code




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 8 of 12
Python in the Browser                                                                          01/06/2010 13:45




 Now user-code is able to run. Each inline Python script-tag is executed as if it was one Python module,
 and all other Python files execute as their own modules.

 To allow Python to be indented inside a script tag, the margin of the first line which does not only
 contain whitespace is removed. Line numbers in the HTML are preserved, so error messages show up
 correctly.


 So we can write code...
 What about testing it? Well, Python comes batteries included.

         <script type="application/x-zip-compressed"
             src="PythonStdLib.zip"></script>

         <script type="text/python">
             if document.QueryString.ContainsKey("test"):
                 import sys
                 sys.path.append("PythonStdLib")

                           import repl
                           repl.show()


file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 9 of 12
Python in the Browser                                                                               01/06/2010 13:45



                           import unittest
                           ...

 That PythonStdLib.zip file contains the pieces of the Python standard-library that unittest depends on.

 The Python standard library is a little less than 5MB compressed, so it's not unthinkable to include the
 whole thing for development, but for deployment you should just include the dependencies; unittest's
 dependencies are 58 KB.

 When a zip file's filename is added to the path, it is treated like any other directory; import looks inside it
 to find modules. You'll also notice that import repl just worked, even though repl.py isn't in the zip file; it
 was referenced by a script-tag earlier. It works because script-tags actually represent file-system entries;
 doing open("repl.py"), or open("PythonStdLib/unittest.py") would also work.


 Using .NET APIs
 Using WritableBitmap to render fractals.




 Silverlight has a ton of functionality, and as I was only able to discuss a few Python libraries in
 Silverlight, I'll only be able to show a few Silverlight libraries being used from Python, but the entirety
 of Silverlight can be used from Python. See all the features Silverlight provides, as well as how to use
 .NET APIs in-general from Python.

 One interesting API is the WritableBitmap, which gives you per-pixel access to render whatever you
 want. For example, here its used to render a fractal. The number crunching is actually done from C#, but
 called from IronPython.

 As with any computationally-intensive operations, it's a good idea to write them in a static pre-compiled

file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                                 Page 10 of 12
Python in the Browser                                                                           01/06/2010 13:45



 language; for example the scientific-computation libraries for Python are actually written in C, but the
 library provide an API accessible to Python programmers. Unfortunately, CPython puts that
 responsibility on the library developer; not every C library can be directly consumed by Python code.
 However, this example shows that IronPython can call into any C# library, or any library written in a
 .NET language for that matter. This makes it trivial to just begin writing your application in Python, and
 then decide to convert the performance-sensitive sections to C#.

 We could also use the WritableBitmap to hook up to a webcam...


 Silverlight Toolkit
 silverlight.codeplex.com




 A rich set of user interface controls including charting components.


 Try Python




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 11 of 12
Python in the Browser                                                     01/06/2010 13:45




 Questions
           blog.jimmy.schementi.com
           ironpythoninaction.com
           voidspace.org.uk/blog
           trypython.org




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html       Page 12 of 12

More Related Content

What's hot

Defending Against Application DoS attacks
Defending Against Application DoS attacksDefending Against Application DoS attacks
Defending Against Application DoS attacks
Roberto Suggi Liverani
 
Enforce reproducibility: dependency management and build automation
Enforce reproducibility: dependency management and build automationEnforce reproducibility: dependency management and build automation
Enforce reproducibility: dependency management and build automation
Danilo Pianini
 
Web development with Python
Web development with PythonWeb development with Python
Web development with Python
Raman Balyan
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Prof. Dr. K. Adisesha
 
Secure Ftp Java Style Rev004
Secure Ftp  Java Style Rev004Secure Ftp  Java Style Rev004
Secure Ftp Java Style Rev004Rich Helton
 
C#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalC#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalRich Helton
 
2018 20 best id es for python programming
2018 20 best id es for python programming2018 20 best id es for python programming
2018 20 best id es for python programming
SyedBrothersRealEsta
 
Hack language
Hack languageHack language
Hack language
Ravindra Bhadane
 
Easy contributable internationalization process with Sphinx @ pyconsg2015
Easy contributable internationalization process with Sphinx @ pyconsg2015Easy contributable internationalization process with Sphinx @ pyconsg2015
Easy contributable internationalization process with Sphinx @ pyconsg2015
Takayuki Shimizukawa
 
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Tom Johnson
 
Publishing API documentation -- Workshop
Publishing API documentation -- WorkshopPublishing API documentation -- Workshop
Publishing API documentation -- Workshop
Tom Johnson
 
Aop, Metaprogramming and codegeneration with PHP
Aop, Metaprogramming and codegeneration with PHPAop, Metaprogramming and codegeneration with PHP
Aop, Metaprogramming and codegeneration with PHP
Serge Smertin
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.Net
Stefan Schukat
 
FISE Integration with Python and Plone
FISE Integration with Python and PloneFISE Integration with Python and Plone
FISE Integration with Python and Plone
Jens Klein
 
Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2
Sergii Shymko
 
API Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterAPI Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC Chapter
Tom Johnson
 

What's hot (20)

Adobe Flex4
Adobe Flex4 Adobe Flex4
Adobe Flex4
 
Defending Against Application DoS attacks
Defending Against Application DoS attacksDefending Against Application DoS attacks
Defending Against Application DoS attacks
 
Enforce reproducibility: dependency management and build automation
Enforce reproducibility: dependency management and build automationEnforce reproducibility: dependency management and build automation
Enforce reproducibility: dependency management and build automation
 
The windows socket
The windows socketThe windows socket
The windows socket
 
Web development with Python
Web development with PythonWeb development with Python
Web development with Python
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Secure Ftp Java Style Rev004
Secure Ftp  Java Style Rev004Secure Ftp  Java Style Rev004
Secure Ftp Java Style Rev004
 
Proposal
ProposalProposal
Proposal
 
C#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalC#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 Final
 
2018 20 best id es for python programming
2018 20 best id es for python programming2018 20 best id es for python programming
2018 20 best id es for python programming
 
Hack language
Hack languageHack language
Hack language
 
Easy contributable internationalization process with Sphinx @ pyconsg2015
Easy contributable internationalization process with Sphinx @ pyconsg2015Easy contributable internationalization process with Sphinx @ pyconsg2015
Easy contributable internationalization process with Sphinx @ pyconsg2015
 
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
 
Publishing API documentation -- Workshop
Publishing API documentation -- WorkshopPublishing API documentation -- Workshop
Publishing API documentation -- Workshop
 
Aop, Metaprogramming and codegeneration with PHP
Aop, Metaprogramming and codegeneration with PHPAop, Metaprogramming and codegeneration with PHP
Aop, Metaprogramming and codegeneration with PHP
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.Net
 
FISE Integration with Python and Plone
FISE Integration with Python and PloneFISE Integration with Python and Plone
FISE Integration with Python and Plone
 
Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2
 
API Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterAPI Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC Chapter
 

Similar to Python in the browser

Python Web Framework – A Detailed List of Web Frameworks in Python
Python Web Framework – A Detailed List of Web Frameworks in PythonPython Web Framework – A Detailed List of Web Frameworks in Python
Python Web Framework – A Detailed List of Web Frameworks in Python
abhishekdf3
 
Rapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute BeginnersRapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute Beginners
Fatih Karatana
 
CTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxCTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptx
OduniyiAdebola
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech Pune
Ethan's Tech
 
Why Your Next Project Should have Expert Hire Python Developers?
Why Your Next Project Should have Expert Hire Python Developers?Why Your Next Project Should have Expert Hire Python Developers?
Why Your Next Project Should have Expert Hire Python Developers?
EmilySmith271958
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Py Con 2009 Pumping Iron Into Python
Py Con 2009   Pumping Iron Into PythonPy Con 2009   Pumping Iron Into Python
Py Con 2009 Pumping Iron Into Python
Sarah Dutkiewicz
 
Top 10 python frameworks for web development in 2020
Top 10 python frameworks for web development in 2020Top 10 python frameworks for web development in 2020
Top 10 python frameworks for web development in 2020
Alaina Carter
 
Getting Started with Python
Getting Started with PythonGetting Started with Python
Getting Started with Python
Sankhya_Analytics
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptx
Kaviya452563
 
Cmpe202 01 Research
Cmpe202 01 ResearchCmpe202 01 Research
Cmpe202 01 Research
vladimirkorshak
 
MOBILE APP DEVELOPMENT USING PYTHON
MOBILE APP DEVELOPMENT USING PYTHONMOBILE APP DEVELOPMENT USING PYTHON
MOBILE APP DEVELOPMENT USING PYTHON
PriyadharshiniVS
 
Flask
FlaskFlask
Native Mobile Application Using Open Source
Native Mobile Application Using Open SourceNative Mobile Application Using Open Source
Native Mobile Application Using Open SourceAxway Appcelerator
 
OSCON Titanium Tutorial
OSCON Titanium TutorialOSCON Titanium Tutorial
OSCON Titanium Tutorial
Kevin Whinnery
 
intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
ANIKULSAIKH
 
Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Django, What is it, Why is it cool?
Django, What is it, Why is it cool?
Tom Brander
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OS
Cisco Russia
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
LakshmiNarayanaReddy48
 

Similar to Python in the browser (20)

Python Web Framework – A Detailed List of Web Frameworks in Python
Python Web Framework – A Detailed List of Web Frameworks in PythonPython Web Framework – A Detailed List of Web Frameworks in Python
Python Web Framework – A Detailed List of Web Frameworks in Python
 
Rapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute BeginnersRapid Web Development with Python for Absolute Beginners
Rapid Web Development with Python for Absolute Beginners
 
CTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxCTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptx
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech Pune
 
Why Your Next Project Should have Expert Hire Python Developers?
Why Your Next Project Should have Expert Hire Python Developers?Why Your Next Project Should have Expert Hire Python Developers?
Why Your Next Project Should have Expert Hire Python Developers?
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Py Con 2009 Pumping Iron Into Python
Py Con 2009   Pumping Iron Into PythonPy Con 2009   Pumping Iron Into Python
Py Con 2009 Pumping Iron Into Python
 
Top 10 python frameworks for web development in 2020
Top 10 python frameworks for web development in 2020Top 10 python frameworks for web development in 2020
Top 10 python frameworks for web development in 2020
 
Getting Started with Python
Getting Started with PythonGetting Started with Python
Getting Started with Python
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptx
 
Python
Python Python
Python
 
Cmpe202 01 Research
Cmpe202 01 ResearchCmpe202 01 Research
Cmpe202 01 Research
 
MOBILE APP DEVELOPMENT USING PYTHON
MOBILE APP DEVELOPMENT USING PYTHONMOBILE APP DEVELOPMENT USING PYTHON
MOBILE APP DEVELOPMENT USING PYTHON
 
Flask
FlaskFlask
Flask
 
Native Mobile Application Using Open Source
Native Mobile Application Using Open SourceNative Mobile Application Using Open Source
Native Mobile Application Using Open Source
 
OSCON Titanium Tutorial
OSCON Titanium TutorialOSCON Titanium Tutorial
OSCON Titanium Tutorial
 
intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
 
Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Django, What is it, Why is it cool?
Django, What is it, Why is it cool?
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OS
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 

More from PyCon Italia

Feed back report 2010
Feed back report 2010Feed back report 2010
Feed back report 2010PyCon Italia
 
Spyppolare o non spyppolare
Spyppolare o non spyppolareSpyppolare o non spyppolare
Spyppolare o non spyppolare
PyCon Italia
 
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"PyCon Italia
 
Undici anni di lavoro con Python
Undici anni di lavoro con PythonUndici anni di lavoro con Python
Undici anni di lavoro con Python
PyCon Italia
 
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
PyCon Italia
 
Qt mobile PySide bindings
Qt mobile PySide bindingsQt mobile PySide bindings
Qt mobile PySide bindings
PyCon Italia
 
Python: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi geneticiPython: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi genetici
PyCon Italia
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
PyCon Italia
 
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
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
 
Jython for embedded software validation
Jython for embedded software validationJython for embedded software validation
Jython for embedded software validation
PyCon Italia
 
Foxgame introduzione all'apprendimento automatico
Foxgame introduzione all'apprendimento automaticoFoxgame introduzione all'apprendimento automatico
Foxgame introduzione all'apprendimento automatico
PyCon Italia
 
Effective EC2
Effective EC2Effective EC2
Effective EC2
PyCon Italia
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
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
 
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
PyCon Italia
 
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
PyCon Italia
 

More from PyCon Italia (20)

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
 
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"
 
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
 
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.
 
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
 
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

Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 

Recently uploaded (20)

Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 

Python in the browser

  • 1. Python in the Browser 01/06/2010 13:45 Python in the Browser Web Programming with Silverlight & IronPython Michael Foord michael@voidspace.org.uk www.voidspace.org.uk @voidspace Python in the browser with Silverlight & IronPython Introduction Silverlight Say Hello to Vera Getting Started: One JS File External Python Files How it works Loading the Javascript Loading the Python Runtime The IronPython Payload Running the Python Code So we can write code... Using .NET APIs Silverlight Toolkit Try Python Questions Introduction You, the Python developer, use Python because you want to, but in the browser you use JavaScript because you think you have to. With Silverlight you can write Python code in the file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 1 of 12
  • 2. Python in the Browser 01/06/2010 13:45 browser. Silverlight Microsoft browser plugin Now installed in over 50% of browsers (riastats) Cross platform: Windows and Mac, plus Linux with Moonlight Cross browser: Safari, Firefox, IE and Chrome Runs IronPython and IronRuby Sockets, threading, local browser storage APIs Webcam access, out of browser apps IronPython docs at ironpython.net/browser/ IronPython 2.6 - the equivalent of Python 2.6. Silverlight features include: A ui system based on WPF Full access to the browser DOM Calling between Javascript and Silverlight code Out of browser applications Video, streaming media and 'deep zoom' Local browser storage Socket and threading APIs (etc) Lots more... Say Hello to Vera file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 2 of 12
  • 3. Python in the Browser 01/06/2010 13:45 Over 19000 lines of Python code (plus hundreds of lines of xaml) written over a 7 month period by two developers. Getting Started: One JS File Loading IronPython: <script src="http://gestalt.ironpython.net/dlr-latest.js" type="text/javascript"></script> Python in script tags: <script type="text/python"> def onclick(s, e): window.Alert("Hello from Python!") document.button.events.onclick += handler document.message.innerHTML = 'Hello Python!' </script> To develop a Python application in the browser, you just need your favorite text editor; so open it up, create a HTML file, reference dlr.js, and then you can use script-tags for running Python code. file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 3 of 12
  • 4. Python in the Browser 01/06/2010 13:45 External Python Files <script type="text/python" src="repl.py"></script> This creates a console when you add ?console to the url. We can reference Python files as well as inline Python. The console is hooked up to sys.stdout, so your existing text-based Python scripts can come alive in the browser (sans reading from stdin). Also, any print statements you use in the app will show up in the console as well, making it a great println-debugging tool. Let's play around with the page a bit, adding a DOM element and changing it's HTML content to "Ouch!" when clicked: >>> dir(document) [..., 'CreateElement', ...] >>> div = document.CreateElement("div") >>> div.innerHTML = "Hello from Python!" >>> document.Body.AppendChild(div) >>> div.id = "message" >>> div.SetStyleAttribute("font-size", "24px") >>> def say_ouch(o, e): ... o.innerHTML = "Ouch!" ... >>> document.message.events.onclick += say_ouch How it works file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 4 of 12
  • 5. Python in the Browser 01/06/2010 13:45 dlr.js contains a collection of functions for creating a Silverlight control on the HTML page that is capable of running IronPython code. Loading the Javascript file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 5 of 12
  • 6. Python in the Browser 01/06/2010 13:45 By default, just running dlr.js injects a Silverlight <object> tag into the page (immediately after the script-tag) so it can run only DOM-based scripts, and also scans for other script-tags indicating that you want a Silverlight rendering surface, but more on that later. Loading the Python Runtime file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 6 of 12
  • 7. Python in the Browser 01/06/2010 13:45 The injected Silverlight control points to a Silverlight application made specifically to embed the dynamic language runtime, the compiler/runtime/embedding infrastructure IronPython is built on, find all the Python code the HTML page uses, and executes it. The XAP is tiny, as the DLR and IronPython are in separate packages which are downloaded on- demand; the DLR and IronPython are not installed with Silverlight, so they must be downloaded with the application. The IronPython Payload file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 7 of 12
  • 8. Python in the Browser 01/06/2010 13:45 However, if the application depends on the ironpython.net binaries, the user's browser will cache them and they won't be re-downloaded for any other app; almost as good as being part of the installer, while still being able to be open-source. Running the Python Code file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 8 of 12
  • 9. Python in the Browser 01/06/2010 13:45 Now user-code is able to run. Each inline Python script-tag is executed as if it was one Python module, and all other Python files execute as their own modules. To allow Python to be indented inside a script tag, the margin of the first line which does not only contain whitespace is removed. Line numbers in the HTML are preserved, so error messages show up correctly. So we can write code... What about testing it? Well, Python comes batteries included. <script type="application/x-zip-compressed" src="PythonStdLib.zip"></script> <script type="text/python"> if document.QueryString.ContainsKey("test"): import sys sys.path.append("PythonStdLib") import repl repl.show() file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 9 of 12
  • 10. Python in the Browser 01/06/2010 13:45 import unittest ... That PythonStdLib.zip file contains the pieces of the Python standard-library that unittest depends on. The Python standard library is a little less than 5MB compressed, so it's not unthinkable to include the whole thing for development, but for deployment you should just include the dependencies; unittest's dependencies are 58 KB. When a zip file's filename is added to the path, it is treated like any other directory; import looks inside it to find modules. You'll also notice that import repl just worked, even though repl.py isn't in the zip file; it was referenced by a script-tag earlier. It works because script-tags actually represent file-system entries; doing open("repl.py"), or open("PythonStdLib/unittest.py") would also work. Using .NET APIs Using WritableBitmap to render fractals. Silverlight has a ton of functionality, and as I was only able to discuss a few Python libraries in Silverlight, I'll only be able to show a few Silverlight libraries being used from Python, but the entirety of Silverlight can be used from Python. See all the features Silverlight provides, as well as how to use .NET APIs in-general from Python. One interesting API is the WritableBitmap, which gives you per-pixel access to render whatever you want. For example, here its used to render a fractal. The number crunching is actually done from C#, but called from IronPython. As with any computationally-intensive operations, it's a good idea to write them in a static pre-compiled file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 10 of 12
  • 11. Python in the Browser 01/06/2010 13:45 language; for example the scientific-computation libraries for Python are actually written in C, but the library provide an API accessible to Python programmers. Unfortunately, CPython puts that responsibility on the library developer; not every C library can be directly consumed by Python code. However, this example shows that IronPython can call into any C# library, or any library written in a .NET language for that matter. This makes it trivial to just begin writing your application in Python, and then decide to convert the performance-sensitive sections to C#. We could also use the WritableBitmap to hook up to a webcam... Silverlight Toolkit silverlight.codeplex.com A rich set of user interface controls including charting components. Try Python file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 11 of 12
  • 12. Python in the Browser 01/06/2010 13:45 Questions blog.jimmy.schementi.com ironpythoninaction.com voidspace.org.uk/blog trypython.org file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 12 of 12