5/22/2015

Configuring Apache to run Python Scripts and MySQL on Centos

    In order to setup a website based on python, you should install python, apache, and mysql. You may use msyql or mysql-connector to connect mysql.

1. Install Python
     $ yum install python

2. Install Apache
    $ yum install httpd

3. Configure Apache for Python
    $ vi /etc/httpd/conf/httpd.conf

     DirectoryIndex index.py

    
    <Directory /var/www/web/app>
        Options +ExecCGI
        AddHandler cgi-script .py
    </Directory>
   


4. Confirmation

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# enable debugging
import cgitb
cgitb.enable()

print "Content-Type: text/plain;charset=utf-8"
print

print "Hello World!"


5. Install MYSQL
    $ yum install MySQL-python

6. Test Example

# import mysql
import MySQLdb

db = MySQLdb.connect("localhost","user","password","test" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()

print "Database version : %s " % data

# disconnect from server
db.close()


7. Install MYSQL Connector
    $ yum install mysql-connector-python

8. Test Example

# import mysql connector
from mysql.connector import (connection)

cnx = connection.MySQLConnection(user='user', password='password',
                                 host='localhost',
                                 database='test')
cursor = cnx.cursor()

cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()

print "Database version : %s " % data

cnx.close()