Tech Site & Blog Blog about technology & programming

23Oct/090

mod_python and MySQLdb

How to install mod_python and MySQLdb in Debian Lenny?

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?

MySQLdb

I got a few errors while trying to install MySQLdb by using python file.py install. 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:
apt-get install python-mysqldb

And now you can use MySQL from Python.

Example:
#! /usr/bin/python

import MySQLdb
import sys #for exit

try:
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])
sys.exit(1)

cursor = conn.cursor()
cursor.execute("SET NAMES utf8;SET CHARACTER SET utf8;SET character_set_connection=utf8;")
cursor.close()

cursor = conn.cursor()

while(1):
cursor.execute("SELECT * FROM table")
if cursor.rowcount > 0:
rows = cursor.fetchall()
for row in rows:
if row == None:
break
print "Data: %s %s" % (row[0], row[1])

This is an example for UTF-8 charset encoding. I still don't know why I needed to close cursor after executing SET NAMES utf8, 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.

How to install mod_python and use it?

It can be installed by typing following command:
apt-get install libapache2-mod-python

You need to put following code in .htaccess or your Apache's configuration file to use Python:
AddHandler mod_python .py
PythonHandler mod_python.publisher

Now just write Python code, save it as something.py and put it in your website's root.
Comments (0)

Leave a comment