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:
- The (sub)domain must be on one of our Unix servers.
- The script must be located in the cgi-bin directory.
- The file extension must be .py for this to work.
- The file permissions must be 755 (CHMOD). You can set this with an FTP client.
- The syntax must be for Python 2.
- The path to Python is /usr/local/bin/python2.7.
- The path to Sendmail is /usr/sbin/sendmail.
- The file must be saved in Unix format so that the correct linefeed (LF) is used.
- 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()
Recommended links
The following external resource is useful for Python developers: