SlideShare uma empresa Scribd logo
1 de 12
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Defending Against Application DoS attacks
Defending Against Application DoS attacksDefending Against Application DoS attacks
Defending Against Application DoS attacksRoberto 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 automationDanilo Pianini
 
Web development with Python
Web development with PythonWeb development with Python
Web development with PythonRaman Balyan
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
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 programmingSyedBrothersRealEsta
 
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 @ pyconsg2015Takayuki 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 -- WorkshopTom Johnson
 
Aop, Metaprogramming and codegeneration with PHP
Aop, Metaprogramming and codegeneration with PHPAop, Metaprogramming and codegeneration with PHP
Aop, Metaprogramming and codegeneration with PHPSerge Smertin
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.NetStefan Schukat
 
FISE Integration with Python and Plone
FISE Integration with Python and PloneFISE Integration with Python and Plone
FISE Integration with Python and PloneJens 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 2Sergii 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 ChapterTom Johnson
 

Mais procurados (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
 

Semelhante a 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 Pythonabhishekdf3
 
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 BeginnersFatih Karatana
 
CTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxCTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxOduniyiAdebola
 
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 PuneEthan'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
 
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 PythonSarah 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 2020Alaina Carter
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptxKaviya452563
 
MOBILE APP DEVELOPMENT USING PYTHON
MOBILE APP DEVELOPMENT USING PYTHONMOBILE APP DEVELOPMENT USING PYTHON
MOBILE APP DEVELOPMENT USING PYTHONPriyadharshiniVS
 
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 TutorialKevin Whinnery
 
intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdfANIKULSAIKH
 
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-OSCisco Russia
 

Semelhante a 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
 

Mais de 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 spyppolarePyCon 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 PythonPyCon 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 PythonPyCon Italia
 
Qt mobile PySide bindings
Qt mobile PySide bindingsQt mobile PySide bindings
Qt mobile PySide bindingsPyCon Italia
 
Python: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi geneticiPython: ottimizzazione numerica algoritmi genetici
Python: ottimizzazione numerica algoritmi geneticiPyCon 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 fastPyCon 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 pythonPyCon 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 PythonPyCon 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 modulePyCon 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 ntopPyCon Italia
 
Jython for embedded software validation
Jython for embedded software validationJython for embedded software validation
Jython for embedded software validationPyCon Italia
 
Foxgame introduzione all'apprendimento automatico
Foxgame introduzione all'apprendimento automaticoFoxgame introduzione all'apprendimento automatico
Foxgame introduzione all'apprendimento automaticoPyCon Italia
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'EnterprisePyCon 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 & OrbitedPyCon 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.1PyCon Italia
 

Mais de 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
 

Último

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Último (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

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