Dejan Levec

mod_python and MySQLdb

[b]How to install mod_python and MySQLdb in Debian Lenny?[/b]

MySQL is one of greatest databases for web sites, and for applications and it\’s probably most used with PHP. Python is a good language for a lot of things. In my case, I needed some daemons, to do certain tasks. Firstly, I tried with PHP, but it is language for web pages, and it don\’t perform well as a daemon. So then I have to choose which language to use. C++ is powerful but very complex and there are other languages, that could fit me better for this project. I don\’t have a lot of idea about Perl and so I tried programming Python.

I faced two problems in last two days:

1. I had problems with installing MySQLdb

2. How to make and publish a simple website in Python?


I got a few errors while trying to install MySQLdb by using [i]python install[/i]. As far as I searched the Internet, there are some workarounds but neither of them worked for me. And then it hit me. Doesn\’t Debian comes with apt, a great package tool?

Installing this plug-in is very easy with apt. You just need to run following command:
[quote]apt-get install python-mysqldb[/quote]
And now you can use MySQL from Python.

[code]#! /usr/bin/python

import MySQLdb
import sys #for exit

conn = MySQLdb.connect(host=”localhost”, user=”root”, passwd=””, db = “database”, charset = “utf8”, use_unicode = True)
except MySQLdb.Error, e:
print “Error %d: %s” % (e.args[0], e.args[1])

cursor = conn.cursor()
cursor.execute(“SET NAMES utf8;SET CHARACTER SET utf8;SET character_set_connection=utf8;”)

cursor = conn.cursor()

cursor.execute(“SELECT * FROM table”)
if cursor.rowcount > 0:
rows = cursor.fetchall()
for row in rows:
if row == None:
print “Data: %s %s” % (row[0], row[1])[/code]
This is an example for UTF-8 charset encoding. I still don\’t know why I needed to close cursor after executing [i]SET NAMES utf8, [/i]but this code should work without a problem.
After my daemon feetched all needed data, I need to display it through web browser. PHP came to my mind, but if one thing is in Python, why not make other thing to? So for that I needed mod_python.

[b]How to install mod_python and use it?[/b]

It can be installed by typing following command:
[quote]apt-get install libapache2-mod-python[/quote]
You need to put following code in .htaccess or your Apache\’s configuration file to use Python:
[quote]AddHandler mod_python .py
PythonHandler mod_python.publisher[/quote]
Now just write Python code, save it as and put it in your website\’s root.

Leave a Reply

Your email address will not be published. Required fields are marked *