Python

Running Python as a CGI (Common Gateway Interface) script at Loopia requires a Unix-based hosting account, a specific file layout and a small .htaccess (Apache configuration) tweak. This article lists the requirements, shows a minimal example and explains how to connect to MySQL from Python.

Requirements for running a Python CGI script

To run a CGI script at Loopia, the following is required:

  1. The (sub)domain must be on one of our Unix servers.
  2. The script must be located in the cgi-bin directory.
  3. The file extension must be .py for this to work.
  4. The file permissions must be 755 (CHMOD). You can set this with an FTP client.
  5. The syntax must be for Python 2.
  6. The path to Python is /usr/local/bin/python2.7.
  7. The path to Sendmail is /usr/sbin/sendmail.
  8. The file must be saved in Unix format so that the correct linefeed (LF) is used.
  9. The file public_html/.htaccess must include SetEnv HOME.

Code example

A minimal Hello World CGI script in Python looks like this:

#!/usr/local/bin/python2.7
# -*- coding: UTF-8 -*-
print "Content-type: text/html"
print
print "Hello, World!"

Support scope for scripts

Our support does not cover script-related problems that are not caused by one of our servers or similar, and we are unable to assist you with your programming.

If you have a problem with a script and would like us to look at it, send us the path to the script, a brief explanation of what you are trying to do and any error messages you receive.

Connect to database

You can also connect to MySQL databases from Python. To do so, use a module named MySQLdb. The sample code below connects to a database and retrieves the MySQL version:

#!/usr/local/bin/python2.7
import MySQLdb
print "Content-type: text/html"
print

db = MySQLdb.connect("server", "user", "pass", "db")
db_cursor = db.cursor()

db_cursor.execute("SELECT version()")
row = db_cursor.fetchone()
print  row[0]
db_cursor.close()

db.close()

The following external resource is useful for Python developers:

Was this article helpful?

Related Articles