Suds cache

December 12, 2012

I’m not a fan of cache where they are not needed, because it can turn a simple task into a no-so-simple task, specially when you don’t expect a cache to exists. This happens to suds, the probably best web service access package existing in python. It uses a cache with a default duration of one day stored in /tmp/suds. That cache only cache wsdl and xsd.

I see this feature could have huge advantages to projects using lots of wsdl and xsd under heavy load, because wsdl and xsd don’t change that often,  however its default values could lead to a headache, because you (at least not me) don’t expect to be a cache at all, and, after you realize there are a cache, you wouldn’t expect to be stored in disk.

To purge the cache, well in my case just the entry of the wsdl I need to be reloaded, it works to remove the file containing it.


Cadenas y Tuplas

April 24, 2012

Esta tarde he estado trabajando en una aplicación y me ha ocurrido una cosa curiosa, no es que no me hubiera ocurrido antes, pero no me había llevado tanto tiempo darme cuenta.

>>> a = "NIF"
>>> type(a)
<type 'str'>
>>> a = "NIF",
>>> type(a)
<type 'tuple'>

La moraleja de la historia es que una coma, puede tener entretenido veinte minutos.

No obstante, estoy seguro de que volveré a tropezar en la misma piedra.


La historia se hace como se puede

April 20, 2012

Decía hace unos días la presidenta argentina Cristina Fernández de Kirchner que la “Historia se hace como se puede”. Esto unido a que los últimos días he podido rescatar mi faceta como desarrollador me ha hecho darme cuenta de que tiene razón. Siempre pensé que soy más un desarrollador que un administrador de sistemas o de servicios, pero en mi vida profesional esta última faceta siempre ha sido más importante que la primera.

Desde hace unos meses cuando dejé Galotecnia, no he podido dedicarme en profundidad a desarrollar, que es lo que realmente me apasiona, pero esto ha cambiado en las últimas semanas. Ayer fue uno de los días en los que más he disfrutado de mi trabajo en los últimos meses.

Como siempre sigo “picando” Django, y la aplicación que me ocupa está muy dirigida por los datos (data-driven) esto hace que haya que buscar un mecanismo para poder pasar de pre-explotación a explotación con nuevos datos. Básicamente se me ocurren tres aproximaciones:

  • Utilizar initial_data
  • Utilizar south
  • Utilizar scripts fabric

En condiciones normales me decantaría probablemente por las “data-migration” de south, pero la aplicación utiliza una base de datos no soportada (no preguntes), así que esto representaba una gran oportunidad para trabajar con fabric. Aunque fabric no está diseñado exclusivamente para esto su integración don Django permite importar los modelos y crear las entradas que sean necesarias. Anteriormente teníamos unos scripts hechos en una mezcla entre python y bash para cargar algunos datos, pero estos no estaban actualizados, así que ahora ya podemos usar fabric para eso.

Por otro lado he podido probar bootstrap que es algo que llevaba algún tiempo queriendo hacer. Yo no soy un diseñador y contar con una herramienta como esta me parece muy positivo. Sin embargo creo que no voy a poder profundizar mucho en esta herramienta con este proyecto. Ya habrá más proyectos!.

Hoy me toca seguir trabajando en este proyecto. En principio tendré que llamar a un procedimiento almacenado en una base de datos Oracle que es algo que tampoco he hecho nunca, aunque he leído que es relativamente sencillo

Una cosa “chula” que hice ayer fue implemenar un Mixin que permite validar un NIF, NIE o CIF español. En “django.contrib.localflavor.es” hay un tipo de form field que permite hacer esto (aunque creo que la validación del NIE es incorrecta), pero en mi formulario se almacena por separado el tipo de documento identificativo y el propio documento. Hice un pequeño mixin que contiene un método clean que tiene en cuenta todas las posibilidades, las clases que hereden de forms.ModelForm o forms.Form y este mixin pueden aprovechar esta validación lo cual, teniendo en cuenta que se usa en varios formularios por toda la aplicación, es muy deseable.


Using itertools

June 1, 2011

Some time ago I wrote a snippet to make combinations in lottery games (49/6). I did it using six nested for loops, so it wasn’t the best approach. Now we have euromillions and I’m interested in doing same thing for this new game. But this time, I’ll use itertools.

Euromillions is quite simple. There are numbers and stars. A combination is valid if it contains 5 numbers (1,50) and 2 stars (1,9). In this first post, I’ll focus in, given a list of numbers and stars, generate all valid combinations with them.

The first step is to make all the available combinations with the numbers. Let’s assume self.numbers has a list of numbers between 1 and 50:

import itertools

valid_number_combs = itertools.combinations(self.numbers, 5)

Now we should do the same with stars. It’s pretty the same

import itertools

valid_number_stars = itertools.combinations(self.stars, 2)

Finally we should combine them using a cartesian product

valid_combs = itertools.product(valid_number_combs, valid_stars_combs)

And that’s all (folks). It’s pretty simple, but perfomance it’s great. In my personal computer it takes just 9 seconds to generate all available combinations with all numbers (1,50) and all stars (1,9). There are 76.275.360

Visit the github of the project for the code.

In the next post I’ll focus in provide high level filters such as limiting the number of odd/even numbers allowed in the same combination.


Django on Netbeans 6.5

November 21, 2008

I developed using VIM and konsole using Python and Django. Some time ago Carlos Ble suggest me to use and IDE. The I try Eclipse + PyDev for a time, but never felt comfortable with it. Since Netbeans team decide to include Python in the supported languages Netbeans could work with; I decide to give it a chance.

While Django is not fully supported itself, I feel Netbeans much more fluent than a Eclipse. Netbeans is not perfect but, on my view, fits my needs more than Eclipse do. I’ll try to use this platform for a while before claim to be THE IDE.

Using Django with it is possible using the same trick I used with Eclipse. Set manage.py as the main file and runserver --noreload as argument. I didn’t success trying to do step-by-step debugging (I didn’t spent more than two minutes trying).

To be the “perfect” platform for Django developing Netbeans needs:

  • Be able to create a django project
  • Be able to create django apps into a project
  • Be able to run manage.py shell
  • Be able to manage DB (At les manage.py dbshell
  • Manage Django tests (manage.py test)
  • Find method usage in templates
  • WYSWYG template editor

The last one is not a real need but it would be great.

Even lacking all this features, I think is probably the best IDE for Django I have ever tried.


Python platform for development

November 18, 2008

Most develop companies use to choose a development platform for all its projects. While this is probably not a good idea for big ones, I realize than doing so has some advantages for small ones. Get specialized is important in order to achieve the best productivity.

There are several platforms you can choose:

  • .Net/Mono
  • Java
  • Others

The first two are the ones most companies choose. Probably the most important features for those are they are quite extended, it’s possible to develop for a lot of  devices, has great IDEs, etc.

I would like to mention that Python at this level. Since Django became important in the web applications scenario, developers coming from PHP, Java and others has given it a chance, you can develop desktop applications (QT, wxWindows, etc.), web applicatrions (Django, Turbogears, etc.), mobile applications (PyS60, PythonCE, etc.). There are some IDEs such as Eclipse and Netbeans (6.5 or greater).

Python is much more faster to develop than Java (and probably .Net) as you can perform quite complex operation in a really simply manner, while it keep the code clean and readable due to its blocks (not like Perl).

On the other hands it miss namespaces (can be simulated some way using packages) and private variables.

On my view Python is one of the most interesting alternative to the major established develop platform.


About Django

August 19, 2008

Django is a web development framework focus in the rapid web applications development based in the DRY (Don’t Repeat Yourself) philosophy. This philosophy means is a well-known technique in software development and, when talking about Django, it means most of common task are performed really easy.

Once of the more interesting features is the project architecture; which allows to develop some kind of components, and use them in all your projects. While I’m quite focus in Django (most of my projects use this framework) I will start blogging about this topic here. This first post is just for announce my intention.