Archive for the ‘Ordenadores’ Category

Zope3 for Djangoers. Part 1: Installation

Monday, September 10th, 2007

I’m been working on a couple of Django projects for two months and I must say it’s a great platform for making web applications. Even when this is not the first time I play with Django. I tend to forget things too easily…

Having said that I must say I still prefer another Python web framework. One that’s pretty big but at the same time it’s small. One that it’s new but at the same time quite old. Yes, I’m talking about Zope. Zope3 precisely.

But I still think there is no perfect framework and each one has its strengths and its weaknesses. So, as always, you should study your requirements and your problem and decide which tool is best for you. As an overly simplified statement I’d say take Django for small 3-5 months projects that won’t change in the future and take Zope3 for everything else. Don’t use the same hammer for every nail.

Now, one of the things Django gets much better than Zope3 is documentation. It’s much easier to get started with Django not only because it doesn’t have a component architecture but because its tutorial and the rest of documentation really rocks.

I’ll try to write a series of posts to give the Zope3 newbie a little bit of knowledge so he/she doesn’t get lost in the Zope3 forrest. And more important, I’ll write them from a Djangoer perspective so you can always compare both frameworks.

Note of caution: in the zope3 world there are a lot of ways to do the same things. You may like this or not but that’s the way it is. In these articles I’ll just choose one of such ways. Probably not the best and hopefully not the worst. Just don’t think it is the canonical zope3 development process. I don’t think there is such one.

In this first article we’ll talk about installation. In Django you just need to have Python installed in your box and a database management system like sqlite, Mysql or Postgresql. That’s pretty much everything you need. Then you write this command:

django-admin.py startproject DJProject

and it creates an environment where you can start writing your code. Actually your are supposed to create applications inside of your project. I don’t like this wording since for me, a project is an application most of the time. Usually I split my project in components following best practices but they are not applications by their own. I know, Django lets you live without creating apps but things get out of the main road and you start living by your own. So let’s be good citizen and create our application:

cd DJProject
./manage.py startapp DJApp

Finally if you want to start your development server all you have to do is type this command:

./manage.py runserver

Ok, let’s jump into the zope3 side. In the old days Zope was a big fat framework and your app was just a module that you hooked into it. Now recently Zope3 has been splitted into lots of small components distributed as Python eggs. This approach has the advantage that you only use what you need keeping it simpler. The disadvantage is that usually you don’t know what you need :-) At least at the beginning. With some practice everything get easier.

Zope3 doesn’t currently work with Python 2.5 due to some changes in the C extensions mechanism that the 2.5 version introduced. There is quite a lot of C code in Zope3 to optimize things: some examples are the ZODB and the security system. That’s why you should stick to 2.4 until the 2.5 support is finished.

To work with Python eggs you need Easy Install which is the tool than manages them. Installing it is super simple:

wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py

This will download everything needed to get started. Next step is install zopeproject. It is a great tool to start a Zope3 project. Its philosophy is that Zope3 is just a library and your app should use that library, not the other way around. It creates a WSGI application with a lot of default configuration made for you. Check out this great article to learn why WSGI is such a great thing. Ok, let’s get back to our project:

easy_install zopeproject
zopeproject Z3Project

The last command will ask you for a directory to place the zope3 eggs. This way other applications can use those eggs without duplicating them. It will also ask you for an administrator username and password. Something similar to what you get when you syncdb your Django project after adding the django.contrib.auth application.

Now you have a Z3Project directory pretty similar to your myproject Django directory. Running an http development server is quite simple:

cd Z3Project
bin/paste serve deploy.ini

But wait, I’ve got a bunch of files I don’t understand!, what are they for? And where is my code supposed to live? Well, don’t panic. I’ll try to answer these questions. The environment we just created is managed by buildout. This software handle the dependencies for your project and create/update the starting points for running, testing and debugging it among other things. These are the files you get:

  • setup.py: it’s a regular distutils file that says how to make an egg for your application. The important thing is that it lists the list of eggs your app depends on.
  • zope.conf: them main zope configuration file. You put your database here and the ZCML file the application will load on startup. Kind of a part of the settings.py file of Django.
  • site.zcml: the file which configures the component architecture of Zope. More on this later.
  • buildout.cfg: the buildout configuration file that basically tells buildout to build the egg each time it is executed taking care of the dependencies and to update the scripts in the bin directory.
  • deploy.ini: as we use Paste for the http server, this file tell it which port and IP to use.

And your code is supposed to live in the z3project subdirectory inside the Z3Project that zopeproject created. You will see a configure.zcml and an application.py files inside that directory, that is a Python package actually. The configure.zcml is included from the site.zcml we already saw and it loads a bunch of sane defaults for Zope3. It’s also the place where you should register your own components. The application.py defines a WSGI application factory that Paste will use to run the http server.

We’ll see how to write our models in the next article. See you then!

Repeat after me: Javascript is not Python

Wednesday, August 29th, 2007

I guess I’m too used to the Python programming language that whenever I have to write simple Javascript functions I keep making the same mistakes. I tend to write as much functionality as possible in the server side (Python :) ) but in order to create rich user interfaces I have to use the client side (Javascript :( ) and things like this happens:

function addTopic(topic) {
    var input_attrs = {
        type: "checkbox",
        checked: "checked",
        name: "topics",
        value: topic,
    };
    var li = Builder.node('li', [Builder.node('label', [Builder.node('input', input_attrs), topic.title])]);
    $("topic_list").appendChild(li);
}

For those of you who are curious, yes I’m using Script.aculo.us and Prototype libraries here but here is the point: There is a syntax error in the previous code, one that Firefox (and thus Firebug) won’t catch but one that Internet Explorer will. The funny thing is the Internet Explorer error message:

Error: Expected identifier, string or number

So, anybody can answer me: is the trailing comma a real Javascript syntax error or just another Internet Explorer flaw?

The display:inline vs whitespace battle

Tuesday, August 28th, 2007

Yesterday I spent quite a lot of time debugging an annoying CSS issue. I wanted to make an horizontal navigation bar so I started using this markup:


<ul>
<li><a href="/section1/">Section 1</a></li>
<li><a href="/section2/">Section 2</a></li>
<li><a href="/section3/">Section 3</a></li>
<li><a href="/section4/">Section 4</a></li>
</ul>

In order to make the list horizontal there are two CSS techniques you can use: 1) float everything or 2) use display: inline. I decided to use option 2) since it is less intrusive and I didn’t want to change the rest of the page layout.

So this is how the CSS looks like:


ul { display: inline; }
li { display: inline; border: 1px solid black; }

My problem was that there was some unwanted space between the list elements that made them difficult to stylish properly. After trying everything on earth to fix it I google for a while until I found the offending thing.

As you make the elements inline whitespace matters and the new line characters in the markup are the ones making the little margin between the list elements. You can fix this problem putting all the elements in a single line but that’s not very readable and it’s quite ugly. So this is how I fix it:

<ul>
<li><a href="/section1/">Section 1</a></li
><li><a href="/section2/">Section 2</a></li
><li><a href="/section3/">Section 3</a></li
><li><a href="/section4/">Section 4</a></li>
</ul>

A creative job offer

Sunday, August 12th, 2007

Today I got a pretty creative email from the Zope3-Users mailing list. It seems they are hiring super heroes. I can’t expect less from a company with such a name….

Running Maemo scratchbox on Fedora 7

Tuesday, August 7th, 2007

The Maemo SDK runs on top of Scratchbox, which has some problems with Fedora kernels and memory managers. If you see an error like this when trying to log in in your scratchbox environment:


Inconsistency detected by ld.so: rtld.c: 1192: dl_main: Assertion `(void *) ph->p_vaddr == _rtld_local._dl_sysinfo_dso' failed!

Then you can try this:


# su -
# echo 0 > /proc/sys/vm/vdso_enabled

Note that the maemo-sdk-install_3.1.sh script will fail if you don’t disable the vdso kernel feature as above.

La red de casa

Saturday, August 4th, 2007

El otro día hice inventario del cacharreo que tengo en casa y tengo que admitir que me sorprendí al darme cuenta de que tenía más máquinas conectadas en red de las que en principio creía:

red-casa

Un breve comentario sobre cada una:

  • El cable modem Motorola es el segundo que uso en mi conexión a Internet y me lo dieron los de Supercable, luego Auna, y ahora Ono. El primero murió en una subida de tensión.
  • El router wifi neutro Linksys WRT54Gv5 también es el segundo que tengo ya que el primero, un WRT54Gv2 también murió por las mismas causas que el cable modem. Me gustaba más el primero ya que tenía Linux dentro y estaba bien entrar por ssh y ajustar las iptables a mano. Con el que tengo ahora me tengo que limitar a la interfaz web.
  • El PC Clónico lo compré el año pasado y es un AMD64 de doble núcleo con 2 Gigas de RAM. Bastante bien para programar a diario e incluso para jugar a juegos como el Doom III. En verano hace un ruido bastante feo así que este año le he comprado una fuente sin ventilador y algo se ha notado.
  • El ordenador negro pequeñito (en vertical mide meno que un boli) tiene dentro mi placa EPIAM1000, una gran compra que hice hace ya casi 4 años. Antes la tenía en un tupperware pero el año pasado decidí darle el alojamiento que merece. Tiene 256 MB de RAM y un disco IDE de 120 Gigas. Ahora mismo sirve mi blog y algunas cosillas más sin problemas.
  • El portatil me lo compró la empresa estas navidades y tras muchos problemas con los repartidores de DELL (UPS) conseguí que llegará a casa. Es un Dell XPS 1210 y estoy muy contento con lo poco que pesa, lo poco que ocupa y lo rápido que va.
  • El Internet Tablet PC (así lo llaman los de Nokia) N800 es una pijada muy útil cuando quieres ver cualquier cosa de Internet y tienes los ordenadores apagados. O cuando quieres leerte ese PDF tan chulo que has encontrado desde tu cama. O para ver un episodio de la serie de turno también desde tu cama. Este N800 no fue gratis como el anterior N770 pero me dieron un descuento por desarrollador y me salió muy baratico.
  • Y por último la Wii, mi adquisición más polémica de estas navidades pero de la que más contento estoy. Recientemente me he pasado el Resident Evil 4 y he de decir que desde pequeño había querido tener una consola y esta es la primera que tengo. Todo un acierto y si no, preguntad al que pasa por mi casa y se echa un tenis en pista cubierta.

Y ahora algunas curiosidades sobre estas máquinas:

  • Tres de ellas usan Fedora Linux, una de ellas la versión Core 6 y las otras dos la versión 7.
  • Nota freak: estos son los nombres de algunas: nyarlathotep, sub-nigurath, yog-sothoth. Me falta por bautizar otras tres.
  • Dentro de poco la familia se ampliará con el PC de Ana, su Nintendo DS y su N770. Veremos a ver si me sale más rentable montar un cluster.
  • La red Wifi la tenía abierta para el uso y disfrute comunal hasta hace poco pero la tuve que proteger con WPA cuando los vecinos no supieron distinguir entre ver su correo/navegar por páginas web y bajarse la serie completa de Bola de Dragón del eMule.
  • En el dibujo, las lineas azules denotan conexiones cableadas y las lineas naranjas conexiones inalámbricas

Demasiado spam para Mailman

Monday, July 23rd, 2007

Esta mañana he ido a actualizar el gestor de listas de correo Mailman que tenemos en Sicem cuando en el proceso de postinstalación Debian me dice que no se puede actualizar el Mailman porque hay mensajes pendientes de moderación.

Entonces recuerdo que la última vez que intente moderar dichos mensajes no pude hacerlo con la interfaz web que mailman tiene para eso (http://localhost/mailman/admindb/lista) ya que dicha web se colgaba y nunca terminaba de generarse correctamente.

Pero, ¿de cuánto spam estamos hablando? Muy fácil:

root@linuxserver:/var/lib/mailman# du -h data/
540M data/

La verdad es que es mucho tiempo sin barrer la casa y las esquinas están ya redondas de tanta basura.

Afortunadamente Mailman ofrece scripts para esta tarea y podemos resolver el problema desde la linea de comandos:

root@linuxserver:/var/lib/mailman# find data -name heldmsg-gazpacho-* -print | xargs bin/discard

Problema resuelto :-) gracias a esta faq