Mostrando entradas con la etiqueta python. Mostrar todas las entradas
Mostrando entradas con la etiqueta python. Mostrar todas las entradas

Python virtualenv for Google App Engine and Flask

Ok, this was so easy I couldn't believe it. First Download the App Engine SDK. Then install virtualenv if you don't already have. Create a new folder, for example, /opt/environments/gae and do some virtualenv magic:

$ cd /opt/environments
$ mkdir my-gae
$ virtualenv my-gae

New python executable in my-gae/bin/python
Installing distribute....done.
Installing pip....done.

Great, now I installed the SDK inside the virtualenv folder:

$ cd my-gae
$ unzip ~/Downloads/google_appengine_1.7.7.zip
$ mv google_appengine google_appengine_1.7.7
$ ln -s google_appengine_1.7.7 gae

You should be left with something like this:


├── bin
├── gae -> google_appengine-1.7.7
├── google_appengine-1.7.7
├── include
├── lib
└── local

This will allow us to update our GAE SDK version without much hassle. Now let's configure the SDK for our new virtualenv. First, edit the file "bin/activate" to look like this:

PATH="$VIRTUAL_ENV/bin:$PATH"
PATH="$VIRTUAL_ENV/gae:$PATH"   # New line for GAE
export PATH

Next time you run "source bin/activate" that line will add the SDK dev_appserver.py executable to our path.

Finally, we need to add our path configuration for the GAE path. Create a new file lib/python2.7/site-packages/gae.pth with the following:

$ cat lib/python2.7/site-packages/gae.pth
/opt/environments/my-gae/gae
import dev_appserver; dev_appserver.fix_sys_path()

Let's see if everything works.

$ cd /opt/environments/my-gae
$ source bin/activate
(my-gae)
$ dev_appserver.py
usage: dev_appserver.py [-h] [--host HOST] [--port PORT]
                        [--admin_host ADMIN_HOST] [--admin_port ADMIN_PORT]
...
dev_appserver.py: error: too few arguments
(my-gae)

$ python -c "from google import appengine"
(my-gae)

We're done with the GAE SDK, now let's go with Flask, which is a bit of a pain, specially Flask-Babel. The easiest thing to do is to use one of the already set up projects like flask-appengine-template or http://gae-init.appspot.com/ which include everything you need.



Stars filter for Jinja2 + Bootstrap

Here's a simple Jinja2 filter to add stars to a template:

Jinja2 template datetime filters in Flask

Well, I'm really liking Flask for the moment. It's light, convenient and well documented. Also, Jinja2 is quite powerful and things are building up pretty fast.

A filter alters a variable in a template. It's mostly for formatting purpose. In the template, it's separated from the variable by a pipe character (|). See Template Designer Documentation for details. There's a bunch of builtin filters, covering a wide range of cases. But sometimes, you may need more. Fortunately, it's pretty easy to add new Jinja2 filters in Flask.

In Jinja2 a filter is a block of code that is applied on user demand on a given variable in a template.

 See Template Designer Documentation for details. There's a bunch of builtin filters, for many different things. In our task at hand, we don't have a filter to localize dates, so let's build one.

First, you need to have Flask-Babel up and running. Next we will create our filter:


On your Jinja2 templates, you only need a datetime and apply the date filter:

{{ obj.date | date }}

Or pass it a different format

{{ obj.date | date(_('%%Y.%%m.%%d')) }}

The only "magical" parts here is the gettext('%%m/%%d/%%Y') and _('%%Y.%%m.%%d'). Now you can add to your different .po files the different formats to use for each language.


Hello World Flask and NetBeans

Let me explain how easy it's to get started with developing a Python backend with tools as NetBeans, virtualenv and Flask.

First, download the latest version of NetBeans 7.3 PHP (this is the lightest version). After installing it, install the Python plugin repository:

http://deadlock.netbeans.org/hudson/job/nbms-and-javadoc/lastStableBuild/artifact/nbbuild/nbms/updates.xml.gz

(You might also want to remove the PHP related plugins)

After restarting NetBeans we're ready to setup our Python virtual environment. In Debian based distributions install with:

$ sudo apt-get install python-virtualenv

Next we setup our first environment flask-env:

$ mkdir python-environments
$ cd python-environments
$ virtualenv flask-env
$ cd flask-env
$ source bin/activate
$ mkdir apps

Inside flask-env you should get something like:


.
└── flask-env
    ├── apps
    ├── bin
    ├── include
    ├── lib
    └── local

This is fairly the same structure you'll see in Python's site-package folder.

To setup NetBeans to use the new virtualenv we'll need to create a new "Python platform" which you'll find in Tools -> Python Platforms. Simply create a New platform and point it to the virtualenv python binary in python-environments/flask-env/python/bin/python

Finally, let's setup Flask for our Hello World example. Go back to your console were you executed source and execute:

(flask-env)$ easy_install Flask

Create a new Python proyect on NetBeans in the apps folder of your virtual environment and specify the new Python platform you just created (you can set it as default).




Copy/paste the Hello World example from Flask site, click on Run and point your browser to http://localhost:5000/ 


Move windows around in XFCE

There's this cool feature in Unity and MacOS (that I know of) where you can use some keybinding to place windows as blocks in your screen, like this:




The idea is that by pressing SUPER+LEFT the current window is placed on the left of your desktop.




As mentioned, XFCE doesn't support this out-of-the-box, but it's very easy to implement:



And that's pretty much it the whole script. You'll need to install xdotool which is what does all the magic. To add your own shortcuts, got to "Settings -> Settings Manager -> Keyboard -> Application Shortcuts" and add your own.



As you can see in the screenshot, I saved this script as /usr/bin/window-placer

The options for the script are: -u (up), -d (down), -l (left), -r right & some combinations like -u -l (upper left corner) and so on. The --offset-y and --offset-x options are important if you don't want the window to hide the panels.

Python and Jongo

For some reason or another, I've always found Python support for RDBMS lacking behind Java, specially in the ORM area. Just imagine, there are no officially supported Python drivers to connect to an Oracle database and you must install the Oracle client... ugh!

Anyway, by having a Jongo server connected to your database you don't have to worry about installing any Python modules, you'll only need a standard Python 2.4+ installation with simplejson or Python 2.5+ which already support JSON.

Let's see, for example, an application which accesses the CIDB database and the Car table:

import jongo

class Car(jongo.JongoModel):
    def __init__(self, id=None, model=None, maker=None, fuel=None, transmission=None, year=None):
        jongo.JongoModel.__init__(self)
        self.id = id
        self.idCol = "cid"
        self.model = model
        self.maker = maker
        self.fuel = fuel
        self.transmission = transmission
        self.year = year

class CarStore(jongo.JongoStore):
    def __init__(self):
        jongo.JongoStore.__init__(self)
        self.model = Car
        self.proxy = jongo.Proxy("localhost:8080","cidb","car", Car)

if __name__ == '__main__':
    carstore = CarStore()
    carstore.load()
    for car in carstore.data:
        print car

    c1 = Car(None, "206cc", "Peugeot", "Gasoline", "Manual", 2008)
    carstore.add(c1)
    carstore.sync()

    c1 = carstore.getAt(carstore.count() - 1)
    c1.set('model', "206")
    c1.set('maker', "PPegoushn")
    carstore.update(c1)
    carstore.sync()

    # We need to refresh the object since it has changed after the sync
    c1 = carstore.getAt(carstore.count() - 1)
    carstore.remove(c1)
    carstore.sync()

Since this is Python, the code is pretty straightforward and self documented, right? For more information and examples on working with Python and Jongo check this page.

Video Streaming Linux/iPad

People like to complicate things a lot. I've been reading of ways to stream video to my iPad. When a solution starts with "Install Wine" I give up. Is not that I don't like Wine, it just feels dirty.
Anyway, the problem is that Apple likes to do stupid stuff to put some crazy locks on hardware and software. I really like the iPad so I'm putting up with some of its problems, but this video streaming thing was getting on my nerves until I found OPlayer HD

So, go to your computer and run a simple HTTP server with some Python magic:

$python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"

BTW, you should do this on a folder where you keep your movies.

Now, install OPLayer and go to the web browser it has. Point it to your server: http://192.168.0.2:8000 for example, and watch/download your movies.

Cool!

OPlayer also has a feature in which runs an HTTP server on the iPad. With this, you can upload your movies to the device from your computer, any computer.

Very cool!

On a final note, I was hoping this would be something VLC would bring, but what a disappointment. There's yxplayer, or something of the like, that is supposed to do the same thing. I've not tested it, I liked OPlayer, so I won't bother.

Another thing, the battery drains like crazy when playing a video over the network, so

Código fuente en Blogger con code2blog

Hoy he descubierto una herramienta llamada code2blog:

 

Es una herramienta muy sencilla que funciona como GUI para source-highlight, excelente herramienta de Lorenzo Bettini. Es una herramienta muy sencilla que utiliza PyGTK y Glade y es sólo un fichero de 34K. Para utilizarla primero la descargamos:

wget http://code2blog.googlecode.com/svn/trunk/code2blog

Si tenemos instalado source-highlight ejecutamos con python y listo. Un ejemplo del HTML generado:


def scan_tree(pathname, calls=['_']):
    """Scans a tree for translatable strings."""
    out = StringCollection(pathname)
    for folder, _, files in os.walk(pathname):
        for filename in files:
            filename = os.path.join(folder, filename)
            if filename.endswith('.py'):
                result = scan_python_file(filename, calls)
                if result is not None:
                    for lineno, string in result:
                        out.feed(filename, lineno, string)
            elif filename.endswith('.glade'):
                result = scan_glade_file(filename)
                if result is not None:
                    for string in result:
                        out.feed(filename, None, string)
    for line in out:
        yield line

Monocaffe Connections Manager 0.6

Monocaffe Connections Manager 0.6 está lista para ser descargada. Además de arreglar algunos fallos he añadido una caracteristica genial, un línea de comandos en cluster. Marcando diferentes pestañas y luego escribiendo en la parte inferior, se verá reflejado en todas las pestañas marcadas. De ésta forma podemos trabajar en varias maquinas a la vez.



Tambien he arreglado algunos bugs y añadido otros :-) los podeis ver en el launchpad de mcm en http://launchpad.net/mcm

Finalmente, me gustaria añadir una version hecha en Qt para KDE, pero prefiero continuar afinando las versiones de consola y de GTK, por lo que si alguien está interesado, que me deje un comentario aquí o en launchpad.

Pronto haré una entrada sobre todo el proceso para poder montar un paquete en launchpad para Ubuntu, siempre que me acuerde de todos los pasos, porque es lioso de cojones.

Monocaffe Connections Manager 0.5.3

La primera versión de mcm con el GUI GTK ya está listo para descargarse. La versión en terminal no conlleva cambios importantes. La nueva versión en GTK está evolucionando incluso para convertirse en un reemplazo de las tipicas terminales, con distintas opciones para abrir pestañas en local y hacia las distintas conexiones. Se agradecen comentarios.

New version of mcm with a GTK GUI. The terminal version hasn't changed since all changes apply to the new front-end. The new GTK version is evolving into a full replacement for a typical terminal application, with different options to open tabs on localhost and to the different connections. Comments are welcome.

Screenshots!

Main Window

 
Add a new connection

Estructura aplicaciones PyGTK

Quiero explicaros una de las cosas que veo menos en los tutoriales y es sobre las estructuras de directorios para aplicaciones Python. Sigue una estructura parecida a las de Unix (¿POSIX?). Esta es la que he seguido para mcm y estoy bastante satisfecho con ella, por lo que voy a utilizarla como ejemplo:
  • mcm
    • doc
      • INSTALL
      • CHANGELOG
      • BUGS
      • manpage
    • conf
    • logs
    • bin
      • mcm.sh
    • mcm
      • __init__.py
      • terminal
        • __init__.py
      • common
        • __init__.py
        • utils.py
        • models.py
        • controllers.py
        • exceptions.py
      • gtk
        • __init__.py
        • mcm-gtk.py
        • mcm.glade
        • mcm_icon.png
      • qt
        • __init__.py
        • mcm-qt.gtk
Una aplicación no es sólo el código fuente, por lo que el orden en la documentación, ficheros de configuración y otros, merecen un lugar donde desarrollarse de forma independiente al desarrollo de la aplicación misma.
Cada páquete o modulo de Python es definido por el fichero __ini__.py y serán estos los que podremos importar dentro de nuestros modulos y conseguir un empaquetado bien definido que nos permitira cumplir con facilidad el principio DRY.
De igual forma podemos ver que la misma estrúctura de directorios define un modelo MVC lo que facilita mucho el desarrollo para diferentes presentaciones. En mcm, reutilizamos las clases y métodos definidos para la aplicación CLI en las aplicaciones gráficas para GTK y Qt. Esto lo logramos, en el caso de GTK definiendo distintos eventos que utilizan a los controladores para crear y modificar nuestros modelos. Por ejemplo veamos como añadimos una conexión desde la vista GTK:

  • def add_event(self, widget):
  •     # Obtenemos de distintas formas los datos necesarios
  •     connection = connections.connections_factory(x, y, z, a, b, c, d)
  •     connections.append(connection)
  • def save_and_quit(self):
  •      dao = Dao()
  •      dao.save(connections)
Lo mejor es que esto mismo lo hacemos en la parte Qt y cualquier otra vista que se nos ocurra.

Monocaffe Connections Manager 0.3

He terminado la versión 0.3 de MCM. Si tenemos "dialog" instalado, al ejecutar sin ningún argumento, nos mostrará un menú con los servidores y con pulsar ENTER sobre alguno, abrirá la conexión. También he cambiado el fichero .mcm donde se guardan los datos de las conexiones para utilizar XML y eliminar un pequeño bug que había. También he añadido conexiones FTP.

Podéis descargarlo desde aqui

This software is designed to ease the management of connections to several types of servers. Since I couldn't find any solution to handle all types of connections from a console, mcm was born. The idea is to avoid having to maintain a separate spreadsheet or wiki page with all the servers I usually connect to and keep that monster open during my work sessions.
There are other solutions, but each handled either ssh only connections, or graphical connections (like vnc). Also, this graphical connections managers were designed to have a GUI and a single command from the console is what I wanted.
My main objective is to provide a fast and reliable mean to store the information of this connections and be able to reach them fast and easily.

Click here to download version 0.3

Screenshot!

Monocaffe Connections Manager 0.2

En un par de horas y ya lanzo la versión 0.2, esto es desarrollo ágil. Gracias a bob_f en el canal de #python en FreeNode he mejorado la presentación de las listas. Además de ello he arreglado un fallo con el RDP y bueno, me he acordado que Dropbox permite publicar cosas. Así que aquí os dejo la última versión.

Descargar Monocaffe Connections Manager 0.2

Unas capturas

Monocaffe Connections Manager 0.1

Llevaba algún tiempo con esta idea rondandome la cabeza. Odio tener que abrir una hoja de cálculo o un página en una Wiki cada vez que necesito recordar los datos para conectarme a cierta máquina. Dado que todo esto lo hago desde una consola, otras soluciones que de todas formas no me convencían, funcionan sólo sobre el entorno gráfico (p.e. PuTTy).
Así que, utilizando Python he creado una pequeña aplicación para mantener una lista con todos los servidores a los que me conecto y almacenar nombre, contraseña, conexión, etc. Está listo para funcionar sobre Ubuntu, pero es fácil de modificar para otras distribuciones en caso de ser necesario. Quizás algún día lo añadan a los repositorios de Debian.
Para el futuro me gustaría añadir una interfaz ncurses, GTK y Qt, sólo por hobbie.
Para instalarla:
  1. $tar -xvzf monocaffe_connections_manager-0.1.tar.gz
  2. $cd mcm
  3. $chmod 766 mcm
Si queréis instalarla como es debido:
  1. $tar -xvzf monocaffe_connections_manager-0.1.tar.gz
  2. $sudo mv mcm /usr/share
  3. $sudo chown -R root.root /usr/share/mcm
  4. $sudo chmod 777 /usr/share/mcm/mcm
  5. $cd /usr/bin/
  6. $sudo ln -s /usr/share/mcm/mcm mcm
Supongo que tocara hacer un MakeFile para esto o incluso un .deb
Para descargar
  • $wget http://rapidshare.com/files/296414487/monocaffe_connections_manager-0.1.tar.gz.html
O pulsando aquí
Espero le encontréis utilidad.
El enlace de RapidShare es temporal, por lo que si veo que mucha gente se lo descarga (dejadme un comentario aquí si no funciona y lo arreglo)

Gráficos del uso de memoria en Linux

Que fácil es hacer las cosas más complicadas con Linux. Tengo que monitorizar el consumo de memoria de una aplicación Java que por alguna razón estaba haciendo un overflow. Al final lo resolví, pero quería comprobarlo de una manera rápida y sencilla.
Lo primero, encontrar algo con lo cual medir la memoria del proceso que deseamos monitorizar. Podemos utilizar top pero buscaba algo más, y me encontré este script en Python.
Lo ejecutamos y nos mostrará el consumo de memoria de cada proceso.
A continuación necesitamos ejecutarlo en intervalos regulares y procesar el único dato que buscamos, en este caso, la memoria utilizada por el proceso Java y para lo cual, escribimos un pequeño script


#!/bin/bash

while true; do
sleep 30;
X=$(./mem_info.py | grep java | awk '{ print $7 }');
echo $(date +%s) " " $X >>/tmp/mem_usage.dat;
done


Ahora cambiamos permisos y ejecutamos en background (&). Este script generará cada 30 segundo una línea con dos columnas, la fecha en formato UNIX (1234567890) y el consumo de memoria de todos los procesos java.
Esto en el servidor donde se ejecuta el programa. A continuación en mi estación de trabajo, instalo el único paquete necesario para todo esto que no viene instalado por defecto en Ubuntu, Gnuplot el cual será el encargado de dibujar las gráficas con los datos que le iremos proporcionando.


$sudo aptitude install gnuplot


Ahora vamos a hacer otro script en nuestra máquina para traer el fichero, formatearlo como lo deseamos, crear el gráfico y mostrarlo.


#!/bin/bash

DATA=/tmp/mem_usage.dat
TMPDATA=/tmp/meminfo2.dat
PLOTSCRIPT=/tmp/myplot.gp

echo Buscando el fichero de datos
scp foo@bar:$DATA /tmp/

echo Cambiando fecha por numeros
X=1;
while read line; do
X=$(( $X + 1 ));
echo $X ${line#*\ };
done < $DATA > $TMPDATA

echo Creando Script para Gnuplot

echo "set terminal png" > $PLOTSCRIPT
echo "set output \"/tmp/mem_usage.png\"" >> $PLOTSCRIPT
echo "plot \"$TMPDATA\" title \"Memoria MB\" with steps" >> $PLOTSCRIPT

echo Drawing
gnuplot $PLOTSCRIPT
eog /tmp/mem_usage.png &


El resultado final es el siguiente:



El primer script continua ejecutándose indefinidamente en el servidor y cuando quiera, ejecuto el segundo script y puedo ver como va evolucionando el consumo de la memoria.

Nota: Tengo instalado el Profiler para Java de Eclipse y gracias a esto fue como resolví el problema de la memoria en la aplicación (un proceso dentro de JBoss) pero de igual manera quería ver como se comportaba la memoria del sistema y no pelearme con algún profiler para JBoss.

Nota 2: El consumo de memoria de la JVM es bastante complejo, por lo que puede que las lecturas no sean las reales del consumo de la aplicación (de hecho no lo son), pero dado que
existía un overflow y la memoria se consumía poco a poco, con ver la memoria del sistema podía saber si estaba o no solucionado el problema.