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

5 comments:

Unknown said...

Hello Francois,
The content of your blog is superb and the images are also looking beautiful. I learn some new interesting stuff from your blog. Keep it on.
Thanks,
Mobile phone li-ion Battery

Top Mobile App Development Companies India said...

I appreciate your post which is helpful for mobile app builder.Thanks!!iOS App Development

Unknown said...

Really wonderful article..Please update more articles like this..
Mobile Apps Development Company

Anonymous said...

Many people will still be definitely not certain this choosing devices can be described as shrewd matter what is going on for the most part as a consequence of producers that generate low-priced different watches that do certainly not do the job the right way wax replica watches. Nonetheless listed here What i am saying is the ideal pieces via just about the most dependable online sites available to buy. His or her similarity to the true pieces is usually unquestionable that is since they are having the most focus on sometimes the smallest highlights. With the timepieces to recognise a stunning to giving up top quality for the money and you just realize which is not referred to as idea in the field! Via the web to check out shopper opinions and discover force on your own which usually not only their particular watches are very good, but also most of the customer service network! At times the actual face appearance red, still this orange depiction from your sapphire ravenscroft is definitely the anti-reflective cellular lining belonging to the precious stone, which unfortunately results in a fabulous bluish shade once considered with sure facets. And as the best webpage is having most of the running watches a lot more economical when compared to they usually are, which may be a venture are unable to wish to miss out. Frequently in the event you just spotted a whole new look at product as well as you would like a classic, African american Weekend stands out as the best special occasion to get the item. Along with you should keep in mind in which Christmas is usually forthcoming along with men and women that you experienced would definitely delight in such a product likewise! For one reduced value, I acquired each one of these things via my own follow, so that you can think of this 100 % satisfaction! As with professional watchmakers, backup different watches manufacturers in addition invested in a lot of attempt not to mention made a consistent investigate to improve the significant charasteristics involving pieces. The greatest challenge can be to get the ideal consequences together with the very least prices in order that those looks after is reasonably priced normally. But they also have an amazing project and also figuring out how natural people prefer us are now able to possess a terrific look at fake watches. All the detail of this Switzerland built equipment, typically the classiness of this layout on the observe encounter and additionally control, the interest that will outline atlanta divorce attorneys portion of the keep an eye on, they are really over basically wrist watches http://www.attrinity.com. They are art pieces. However , that will not mean I want to devote a great find to acquire one among mine. On the plus side to me you can find high-quality watches I am able to order that contain each of the classic glimpse which will I am going intended for.

Anonymous said...

I read your article its very informative because the information you provide it's very necessary to find the location. Sometimes we want the long and latitude of any location. so this app is really helpful for me. I use this app for my work. The content or programming code you use on your blog is so simple and understandable.

If anyone want some apps regarding to location please contact us - www.apptunix.com