Showing posts with label brython. Show all posts
Showing posts with label brython. Show all posts

Friday, January 2, 2015

Innovation is not a hotdog

Once upon a time


You would walk in a supermarket, buy hot dogs and hot dog buns. It was a pretty straightforward process. Sausage pack, check. Buns, check.

Then, someone had the idea of making a bun length sausage. Hmm, ok, except that different brand of "bun length" sausages and buns all have different metrics. But hey, that's ok, it was a valiant effort.

More is more


Some time passed, and somebody thought, "hey, let's make a sausage longer than the bun!". Of course, all readers will be quick to point out that there never was a sausage exactly the length of a bun, they were either slightly shorter, or slightly longer. It was just a "more is more" marketing.

What's next


You are probably expecting a sausage to appear on the market "shorter than the bun!". And the circle will be complete. But, which one is the better design? Which one innovates? Same answer to both question: the original design for sausage, which dates back to at least the 9th century BC. Anything beyond that is in the presentation (the marketing).

Tech innovation


Now, back to technology. Let's take the phone, for example. Clearly, going wireless was an innovation. Going pocketable was an innovation. Touchscreen. Haptics. Innovations. But the same tech, just in a different (bigger and bigger, a.k.a. "more is more" marketing) package, is not innovation (*cough* apple *cough* samsung). In fact, one could say there is a clear regression in that field (phones used to have battery life expressed in weeks, could fit in your pocket, even in jogging shorts, could be dropped multiple times on rock hard surfaces without any problem etc)

You can do it


So, why am I talking about all of that? Well, it's my yearly encouragement to truly innovate (see last years post here). But you can't do it in a vacuum. Engage in your local community. If you haven't done so yet, make it a goal this year. Your local programing user groups (Python, Java, Javascript, whatever), maker space or hacker space, robotics, raspberry pi or other creative group, you local coworking, STEM/STEAM school groups etc. Not only will you benefit from attending, by growing your network and your knowledge, but you'll contribute something back to your community, to the society.

Before I sign off for the day, do read my post on innovation in general and personal scale innovation from last year.

@f_dion

Thursday, June 19, 2014

South East Linux Fest, Python Represent

Friday


I'll be presenting at South East Linux Fest (SELF) 2014. According to the final schedule, it is tomorrow, Friday the 20th at 4PM. Right after that will be a BOF in that same room. Come by and talk *nix and Python.

Last year Python was pretty much absent from the conference. Yet it is quite focused on security, and Python is just the right tool for that kind of stuff.

Brousse


That's one project among many I'll be talking about, bringing computing education to people who are usually left without.

Keep an eye on my twitter account and this blog for details. The core of the talk is about Brython.

Video


Apparently, videos of talks will be available after the conference.

@f_dion

Tuesday, March 25, 2014

Upcoming Python talk

Brython: Not Celtic, Pythonic!


Over the past few years, I've had a few A-Ha! moments, as I host project nights, mentor individuals and conduct workshops.

The latest was in front of a large classroom. That's when I realized I didn't have to explain what a shell or a command line was. So what is the Python punchline? It is one of the many anecdotes I'll cover in my talk @ TriPython this week in the Raleigh / Durham area of NC.

What

TriPython March meeting

Where

Bull City Coworking location detail

When

Thursday, March 27th
7PM


François
@f_dion

Sunday, February 9, 2014

Python everywhere: #Brython 2.0

 It's alive


Wow, 15 months later and we are at Brython 2.0!

Changes in Brython version 2.0-20140209-164925



Backwards-incompatible change

=============================
For the sake of namespace isolation, by default, the name of functions and classes defined in Brython are no more available in Javascript global namespace. As a consequence, functions can't be called as event callbacks from HTML tags. For instance, if a function echo() is defined in a Brython script, the following inline code :

    <button onclick="echo()">

will result in a Javascript error such as "name echo is not defined" when the button is clicked

The solution is to define the event callback inside Brython code. The button must have an id :

    <button id="echo">

and the Brython code must include the line

    doc["echo"].bind("click",echo)

Alternatively, to force the name "echo" into the global Javascript namespace, add it as an attribute of the window object :

    from browser import window
    window.echo = echo


Features

========
  • - namespace isolation : in previous versions, the names defined in Brython core scripts were included in the global Javascript namespace, raising risks of conflict with names defined in Javascript programs or libraries. In this version, the only names included in the global Javascript namespace are __BRYTHON__ (used internally) and brython(), the function called on page load
  • - implement sys.implementation with values adapted for Brython
  • - allow syntax del (x, y, z)
  • - use Dan McDougall's pyminifier to reduce size of py_VFS.js
  • - make_dist generates a script brython_dist.js that can be used as a standalone distribution on a centralised server.

Demos

=====
  • - add drop files demo (by Glenn Linderman) and French Python course (using module slideshow) to the gallery

Imports

=======
  • - improved version of py_VFS.js by Billy Earney. py_VFS compiles the standard library to make imports faster. Now packs Python source with JSON instead of base64

Built-in modules

================
  • - browser : add attributes "window" and "document" as alias of respectively "win" and "doc"
  • - add a module browser/slideshow for PowerPoint-like slideshows in Brython, using a custom file format

Bug fixes

=========
  • - issue #174 : string format character % has wrong precedence
  • - issue #175 : Functions should return None by default
  • - issue #183 : re.findall() broken
  • - issue #198 : operator precedence not defined for << and >>
  • - issue #206 : add <noscript> in case Javascript is disabled
  • - issue #208 : bug with try / else
  • - issue #209 : bug in ternary operator
  • - function definions must be evaluated only once, upon function definition
  • - bug with del a[:]
  • - bug with dir() called without arguments
  • - bug in map()
  • - bug with "func(x=1,)" ; "return +x" ; "func(10*-x)"
  • - bug in divmod and round
  • - bug in local_storage method keys()
  • - add attribute __doc__ to class and instance methods

Documentation

=============
  • - updated with the changes introduced in this version
  • - add documentation for the built-in module javascript
  • - translation in Spanish updated by Kiko Correoso

Wednesday, January 1, 2014

2013 Raspberry Pi Python Adventures Review

More work, less social media


2013 kept me quite busy. I worked hard on Dion Research doing digital signage and interfacing with manufacturing equipment. I also took on a new position doing more Python development. And increased quite a bit the number of social events in the local Python community (actual physical events). What this means is that social media interaction slowed down some. This was even worse in the other languages, such as french, spanish and portuguese. The output there was quite spotty. Still, some of the articles and tweets I posted in 2013 were quite popular.

Most Popular


Hardware hacking and Python in the browser were the 2 most popular themes. In fact, in the #1 spot by far in terms of views in 2013 was an article on Brython from December 2012:

http://raspberry-python.blogspot.com/2012/12/brython-browser-python.html

Now, a year later, Brython has been through many changes, including more javascript compatibility (and ongoing restructuring). You can learn more by checking out the Brython documentation.

Soliloquy: I spent a few weeks preparing something on Brython for PyCon, but the talk didn't get accepted, unfortunately, and has left me a bit ambivalent about conferences: Is my time better served building elaborate talks on open source projects I contribute to, for conferences I may not get invited to? Or spending the time on the actual projects coding, or even on this blog?

But not all is a loss for you, the reader, since I'll post some of that material on this blog in the coming months.

The #2 was this article on making your own GPIO cable for the still very popular Raspberry Pi:

http://raspberry-python.blogspot.com/2013/02/making-your-own-raspberrypi-gpio-cable.html


Completing the podium at #3 for 2013 was:

http://raspberry-python.blogspot.com/2013/01/pyhacking-step-by-step.html

Least Popular


The least popular articles were all administrative in nature, such as the announcement of the addition of a contact form. It is clear that very few are interested in these kinds of posts, and they will continue to stay at a minimum for 2014.

2014

I just started yesterday a PTOT[D, W, M] (Python Tip Of The Day, Week, Month...). I'm curious to see how popular that will turn out to be. I'll also be introducing something new to help Windows users to get the most out of Python. Still, I recommend to get yourself a Raspberry Pi running Linux as a sidekick to your Windows machine, you'll be happier that way.

I'm also thinking about covering web.database, browser.local_storage, sqlalchemy, alembic and a few other database related themes.




What are some of the themes you'd like to hear about?


François
@f_dion

Tuesday, November 19, 2013

Project Night: A red Raspberry Pi, 126 LEDs and a job

Project night


Every month, through PYPTUG, we set aside 2 nights for the Pythonistas and Pythonistas to be of the Piedmont Triad community. Tomorrow (wednesday the 20th of November) is one such night.

So what do we do there? The meetup page says:

"Do you have a project you want to show off? Or do you need a second set of eyes on your code? Would you like to hack on an open source project? Perhaps you need help getting a module on a specific platform? Don't have a project but would like to help others or to learn more Python?
Whatever the case may be, project nights are your opportunity to get some help or to help others, so bring your laptop (or Raspberry Pi or whatever device that can run Python) and let's get things going."

Red Raspberry Pi


So, I always show up at these project nights with a few potential projects. For example, hacking on Brython, or writing a good music collection manager in Python, or playing with a red Raspberry Pi. Red? Yes, this kind:

http://www.raspberrypi.org/archives/3195 

Pi Lite


But that wouldn't be a project in itself. I'll bring over a Pi Lite. What is that?

Ciseco Pi-Lite
126 ways to have fun.

Spectrum analyzer? network traffic display? game of life? cool scroller? Who knows what i'll end up doing, but it'll be fun, I'm sure.

A job?


Oh yes, almost forgot. So this project night is in Winston Salem:
Inmar 2650 Pilgrim Court, Winston Salem, nc

And it just happen to be that there are some openings for Python developpers, doing web services and focusing on Python. If that sounds like fun, get in touch.

Winston Salem is a great place to live and work (and that's me saying this, coming from cosmopolitan Montreal). Plus Inmar is migrating downtown pretty soon, in the Wake Forest Innovation Quarter. So come on, take the first step and possibly come and join me and other enthusiastic Pythonistas at Inmar and drop me a note, or even better, email me your resume.

Requirements:
Experience with Python (web services a plus) and with Postgresql (or even mysql).

François
@f_dion


Monday, August 19, 2013

Nouvelle version de Brython: 20130817-141536

Téléchargement de Brython


Une nouvelle version de Brython, Brython-20130817-141536, est maintenant disponible sur la page des téléchargement
 

Changements

Depuis la version précédente :

- import amélioré , on peux utiliser les packages : "import X.Y", "from X.Y import Z [as A]", "from . import X" (corrige le bogue 123)
- le protocole des itérateurs utilise maintenant les méthodes __iter__() et __next__() pour tous les types
- "for" les utilisent aussi
- implémentation des compréhensions améliorée : utilise les dictionnaires global et local (corrige le bogue 129)
- améliorations a la console interactive : http://brython.info/tests/interactive_mode.html
- ajout du type "bytes" (incomplet)
- ajout de balises HTML5 et événements DOM manquants
- ajouts a la documentation en français, ajout d'une section pour les modules spécifiques a Brython ; autres parties traduites
- Bouton sur la page de tests pour exécuter tout les tests et retourner les erreurs
- amélioration du module markdown : les _ et * génèrent du HTML différent, tout comme __ et **
- le mot clé del : utilise la méthode __del__() si elle existe


Bogues

  • - Corrections :
. #78 : map() and filter() return iterator objects, not lists
. #124 : support of CSS attribute "float"
. #125 : add methods copy() and clear() to lists
. #126 : escaped quotes inside strings
. #127 : DOMNode instances comparison methods (__eq__ and __ne__)
. #128 : class inheritance
. conversion des JS objects dans json.js et $JS2Py
. problème avec les itérations sur instances DOMNode



Autres


  • réorganisation : déplacement de JSObject du fichier py_dom.js au fichier py_utils.js
  • galerie : ajout d'un jeu de solitaire qui utilise SVG et le glisser - déposer


Vos retours


L’équipe Brython espère vos retours sur cette version, autant pour nous laisser savoir si vous trouvez  des bogues mais aussi au niveau de votre expérience avec Brython, en joignant et participant aux forums Brython.

De plus nous aimerions entendre parler de vos projets (actuels ou futurs) avec Brython sur appareils mobiles (tablettes, etc) et informatique embarquée (Raspberry Pi, Beaglebone black, Cubieboard, etc), surtout au niveau des écrans tactiles, car nous y travaillons en ce moment. Alors, n’hésitez pas a joindre le forum ou a me contacter directement sur mon blog ou sur twitter.

François
@f_dion

Sunday, August 18, 2013

200000th visitor




Raspberrypi and Python


In February 2013, this blog reached the 100,000th visitor milestone. Tonight, it just past the 200,000th.

This little experiment has been ongoing for almost a year now. As I had mentioned before, I didn't expect a lot of visitors due to the specificity of the blog, but it was something I had to do. Most projects I do for business, I cant talk about, so I've made up some projects specifically for this blog.

The Raspberry Pi has continued on the road to popularity, and this has exposed many people to embedded computing, to software development and electronics, and that is a good thing. Some other subjects that have been popular over the year have been Brython, ZFS and dtrace.

I've seen people I've introduced to the Pi, to electronics or to replicators (ie. CNC, 3D printers, laser cutters), to Python or Brython come up with some really cool stuff in the past year, and that is ultimately quite rewarding.


The visitor 

So, where is this 200,000th visitor from? Surprisingly from the town of Sanford, NC. I say surprisingly because it is only an hour and a half away from Winston Salem by car.

Sanford, NC


François
@f_dion

Saturday, August 17, 2013

Brython 20130817-141536 published

Download Brython


A new version of Brython, Brython-20130817-141536, has just been published on the downloads page



Changes

Here are the main changes since the previous version :

- improved implementation of import, now supports packages : "import X.Y", "from X.Y import Z [as A]", "from . import X" (fixes issue 123)
- the iterator protocol now uses the standard methods __iter__() and __next__() on all types, including built-in types
- the "for" loop implementation has been changed to use these methods
- improved implementation of comprehensions : now uses global and local dictionaries (fixes issue 129)
- improved interactive console : http://brython.info/tests/interactive_mode.html
- partial support of built-in type "bytes"
- add missing HTML5 tags and DOM events
- change documentation in French, add a section for Brython-specific modules ; updated translation of documentation
- add a button on the Tests page to run all the tests in a row and report errors
- improvement to the markdown module : tags _ and * generate different HTML tags, as well as __ and **
- change implementation of the del keyword : now uses the method __del__() if it is defined

Bugs

  • - bug fixes :
. issue #78 : map() and filter() return iterator objects, not lists
. issue #124 : support of CSS attribute "float"
. issue #125 : add methods copy() and clear() to lists
. issue #126 : escaped quotes inside strings
. issue #127 : DOMNode instances comparison methods (__eq__ and __ne__)
. issue #128 : class inheritance
. bugs in conversion of JS objects in json.js and $JS2Py
. bug with iteration on DOMNode instances



Other


  • package organisation : move JSObject from py_dom.js to py_utils.js
  • gallery : add a demo of a solitaire game using SVG drag and drop


Feedback


As always, the Brython team looks forward to your feedback, particularly in terms of bug reports and also in sharing how you are using Brython, by joining and participating in the Brython forum.

We are quite interested in your experience on mobile devices (tablets etc) and embedded devices (Raspberry Pi, Beaglebone black, Cubieboard etc), particularly in conjunction with touchscreens, as we are about to bring further enhancements to Brython. So don't be shy and join the forum. Or at least contact me through my blog or on twitter.

François
@f_dion

Friday, August 2, 2013

A python interactive console in my blog

Brython modes

I had prepped a presentation on Brython for a Python conference and didn't want that to go to waste, so now, dear reader, you get to see all kinds of exclusive material I had made for it. (Don't worry, I'll have plenty more material for PyCarolinas 2013).

The difference is that this is a blog, not a talk, so it will be a good bit more non linear. I'm starting tonight with something very hands on, one of Brython's mode of deployment.

The Brython interactive mode

The brython.js script itself is not included in this page, so it is a hosted interactive mode. We will simply include an iframe to load an interactive console directly from brython.info. This is still quite experimental, as it is found under the tests/ section. It is now using most of my iframe box (was fixed some days back). But it does work pretty well already.

This is basically a zero install, just add the following in your web page and you'll get a brython interactive session (Edited 3-26-2014 to point to new location):  

<iframe src="http://www.brython.info/console.html" width="98%" height="400">Sorry... your browser doesn't support iframe. Time to upgrade or go to <a href="http://www.brython.info/console.html">http://www.brython.info/console.html</a> in a separate tab.</iframe>






So you should see a console above (wont work trough news aggregators). At the >>> | prompt, type:

x = input("yo")

Type the word me in the prompt dialog that will open. Make sure you type exactly that. So what do we have in x? Type the following:

print(x)

me - Ok, that's all nice, but not very exciting. So it does behave like a console. What else can we do?

import webbrowser

So now we have loaded the module webbrowser from the brython standard library (we will come back to that in a future article). Yeah, I know, mind bending, since we are client side. Let's use the module. Type the following:


webbrowser.open("http://en.wikipedia.com/wiki/internet_" + x*2)

Nice! All your base are belong to us, obviously. So, it does take a minute to get the brain wrapped around this concept, but once you do, the world's your oyster. You just have to:

doc <= "think"
:)

Alright, enough geek puns, but it is a friday night afterall. So go and check it all out at http://brython.info . There is documentation in english, french, spanish and portuguese. Feel free to contribute your own translations in markdown format through bitbucket.

If you've been following my blog, you already know about the <= (left arrow) operator. If not, check it out here: http://raspberry-python.blogspot.com/2012/12/brython-browser-python.html

In the early days, brython didn't have a print() keyword. So I had cooked up a quick webprint() that used the <= operator. Of course, 8 months later, we no longer need webprint(). Print works like it should, with stdout. For the interactive mode, it is redirected. Look at the (python) code to see how you can do that by right clicking on the iframe and doing a view frame source (hint, lines 48 to 51).


François
@f_dion


Wednesday, July 31, 2013

Site brython.info em portugues

Site

Algo novo hoje:

em portugues!

Documentação


O site juntamente com a documentação foi traduzido. Tudo graças aos esforços de Yuri Teixeira.

Grupo

Existe tambem um grupo googlegroups em portugues:

https://groups.google.com/forum/?fromgroups=#!forum/brython-pt

François
@f_dion
 

Friday, June 7, 2013

Brython a Toulon



Au programme de Pytong (http://pytong.org/orateurs.html) a Toulon, on retrouve une présentation de Brython (http://www.brython.info), avis aux intéressés!



François
@f_dion

Friday, March 8, 2013

Wanted: speaker for PyCon Brython talk

Anybody going to PyCon 2013 and is available to give a lightning talk? Since there was no way for me to go this year due to scheduling conflict, I'm looking for someone to give a lightning talk on Brython.


www.brython.info

Contact me if you are interested in doing it, as I'll be doing a major revamp of the documentation in English in the next few days. The French documentation is quite a bit more up to date.

François
@f_dion

Tuesday, January 29, 2013

Applications pour téléphones mobiles avec Python

C'est une traduction de iPhone app with Python. J'ai eu une forte demande pour la version française.

Grâce a Brython


L’icône Brython GPS

 

Une vraie app pour iPhone?


Le programme lancé, on y voit un écran de démarrage, comme il se doit:

Splash (ancienne carte de Caroline du Nord)

Mais c'est un programme web, et pas une application faite avec xcode.

Le premier écran, mode manuel


Mode mise a jour automatique

J'essaie?


Il suffit d'aller sur le lien de la galerie de Brython, ici:

gallery/geo.html et sur un iPhone, on l'ajoute a l'ecran d'accueil. On peut maintenant lancer le programme comme une vraie application iOS.


J'ai déjà vu cela, non?


C'est bel et bien une application web, donc basée sur HTML et CSS, mais le code lui même, c'est écrit en Python. En plus, on utilise ici une toute nouvelle fonctionnalité de Brython, en faisant appel a un script Python externe a la page HTML (c'est une nouveauté qui date de cette fin de semaine), plutôt que d'avoir le code a même la page HTML. Cela nous permet une séparation de la présentation, de la logique et du "bling" (le CSS):

Notre HTML


<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <meta charset="iso-8859-1">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1,maximum-scale=1">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <script src="../brython.js"></script>
        <script type="text/python" src="navi.py"></script>
        <link rel="stylesheet" type="text/css" href="navi.css" />
        <link rel="apple-touch-icon" href="icon.png"/>
        <link rel="apple-touch-startup-image" href="splash.png">
    </head>
    <body onLoad="brython()">
        <div id="header">
            <H1>Votre position</H1>
            <div id="switch">
                  <span class="thumb"></span>
                    <input id="refr" type="checkbox" />
                </div>
            </div>
        </div>
        <div id="navarea"></div>
        <div id="maparea"></div>
    </body>
</html>

Application web pour iPhone typique, mais sans jQuery mobile ou autre module du genre. Et pas de onclick dans la page html. L'unique javascript c'est brython.js qui est l’interpréteur Brython même et l'appel a brython() par l'entremise de onload.

Le code Python n'est pas sur la page, mais on voit qu'on y fait reference par src="navi.py"

Allons donc voir ce qu'il y a dans ce fichier navi.py:

Notre Python


# globals #########################
refr = False
geo = win.navigator.geolocation
watchid = 0


# les fonctions ###########################
def navi(pos):
    xyz = pos.coords

    ul = UL(id="nav")
    ul <= LI('lat: %s' % xyz.latitude)
    ul <= LI('lon: %s' % xyz.longitude)

    mapurl = "http://maps.googleapis.com/maps/api/staticmap?markers=%f,%f&zoom=15&size=320x298&sensor=true" % (xyz.latitude, xyz.longitude)
    img = IMG(src = mapurl, id = "map")
    try:
        doc["nav"].html = ul.html  # on met a jour la liste
    except KeyError:
        doc["navarea"] <= ul  # on cree la liste
    try:
        doc["map"].src = mapurl  # on met a jour l'url de l'image
    except KeyError:
        doc["maparea"] <= img  # on cree la balise img

def nonavi(error):
    log(error)

def navirefresh(ev):
    global refr, watchid
    refr = False if refr else True
    if refr == True:
        doc["switch"].className = "switch on"
        watchid = geo.watchPosition(navi, nonavi)
    else:
        doc["switch"].className = "switch"
        geo.clearWatch(watchid)

# au demarrage ###########
if geo:
    geo.getCurrentPosition(navi, nonavi)
    doc["switch"].className = "switch"
    doc["switch"].onclick = navirefresh  # on associe un evenement onclick
else:
    alert('geolocation not supported')

On établis 2 fonctions de rappel (callback). Une si on a notre géolocalisation (navi), et une s'il y a une erreur (nonavi), et finalement, une autre fonction (navirefresh) pour s'occuper de l’événement onclick du contrôle auto refresh dans la barre de menu de l'application. Le démarrage initial se fait par un appel a geo.getCurrentPosition avec nos fonctions de rappel. Ça fonctionne assez bien comme GPS.

Notre CSS

Le CSS étant un peu long, je ne le mettrai pas sur mon blog, mais vous pouvez trouver le code sur le site brython.info ou sur googlecode: SVN repository. Le CSS pour l'interrupteur genre ios 5 a ete emprunté ici: ios-5-style-switch-control

Ce n'est que le début

Alors voila, c'est un point de depart pour faire toute sortes de choses. Un tracker pour le jogging, le velo (avec local storage et synchro par appel ajax) et bien d'autres choses. Vous pouvez désormais faire tout cela avec votre langage favori (Python, bien sur) que ce soit pour votre téléphone mobile ou tablette. Cet exemple est quelque peu spécifique au iPhone (surtout a cause du CSS), mais fonctionne sur Android aussi et peut être adapté facilement aux tablettes. Et cela ne m'a pas pris beaucoup de temps.

Et si vous avez besoin d'aide, n'oubliez pas qu'il existe une liste en francais:
forum/brython-fr

@f_dion

Monday, January 28, 2013

iPhone app with Python

Thanks to Brython


Brython GPS icon

 

Native? Not quite...


The application launches with a splashscreen, like it should

Splash page

But it is really a web application.

Tracking my progress
Automatically refreshes on movement

Can I try it?


Absolutely. Simply point your iphone to the brython gallery url:

gallery/geo.html then click add to home screen. You can now launch it like a native application.


What makes it special?


It's a web application, so of course HTML and CSS, but the code is Python. It leverages the new Brython feature to link to a remote python script, instead of having it inline with the html. This allows a clean separation of presentation, logic and eye candy:

The HTML


<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <meta charset="iso-8859-1">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1,maximum-scale=1">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <script src="../brython.js"></script>
        <script type="text/python" src="navi.py"></script>
        <link rel="stylesheet" type="text/css" href="navi.css" />
        <link rel="apple-touch-icon" href="icon.png"/>
        <link rel="apple-touch-startup-image" href="splash.png">
    </head>
    <body onLoad="brython(2)">
        <div id="header">
            <H1>Your position</H1>
            <div id="switch">
                  <span class="thumb"></span>
                    <input id="refr" type="checkbox" />
                </div>
            </div>
        </div>
        <div id="navarea"></div>
        <div id="maparea"></div>
    </body>
</html>

Your typical iPhone web application, except that there is no jQuery mobile or similar framework. There is no onclick. The only javascript is the brython.js file for Brython itself and the related body onload call of brython().

So let's have a look at the Python code:

The Python


# globals #########################
refr = False
geo = win.navigator.geolocation
watchid = 0


# functions ###########################
def navi(pos):
    xyz = pos.coords

    ul = UL(id="nav")
    ul <= LI('lat: %s' % xyz.latitude)
    ul <= LI('lon: %s' % xyz.longitude)

    mapurl = "http://maps.googleapis.com/maps/api/staticmap?markers=%f,%f&zoom=15&size=320x298&sensor=true" % (xyz.latitude, xyz.longitude)
    img = IMG(src = mapurl, id = "map")
    try:
        doc["nav"].html = ul.html
    except KeyError:
        doc["navarea"] <= ul
    try:
        doc["map"].src = mapurl
    except KeyError:
        doc["maparea"] <= img

def nonavi(error):
    log(error)

def navirefresh(ev):
    global refr, watchid
    refr = False if refr else True
    if refr == True:
        doc["switch"].className = "switch on"
        watchid = geo.watchPosition(navi, nonavi)
    else:
        doc["switch"].className = "switch"
        geo.clearWatch(watchid)

# the setup
if geo:
    geo.getCurrentPosition(navi, nonavi)
    doc["switch"].className = "switch"
    doc["switch"].onclick = navirefresh
else:
    alert('geolocation not supported')

We are setting up 2 callback functions. One called if we have navigation (navi) support, one if we dont (nonavi), and finally a function (navirefresh) to handle the onclick of the auto refresh switch in the title bar of the application. This works pretty decently as a quick and dirty GPS application.

The CSS

The CSS is a bit long so I'm not posting it on the blog, but you can check out the source at the brython.info site or on the SVN repository. The ios style switch CSS is borrowed from this article: ios-5-style-switch-control

The tip of the iceberg

So there you have it. You can now use your favorite language (Python, of course) to write applications for your mobile phone or tablet. This example is slightly iPhone specific (mostly due to CSS), but the same basic structure applies to a variety of mobile devices. And it took no time whatsoever to write this.

@f_dion