The code
#!/usr/bin/env python
import MySQLdb
print \"Content-Type: text/html\"
print
print \"Books
Make sure you're saving the file with correct line endings. i.e. LF only on unix, or CR/LF for Windows. I just recently had the exact same problem...
I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with "
and '
. Do you have any more luck with the following? Can you run it from a terminal just by typing python test.cgi
?
#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
The error in http://dpaste.com/8866/ is occurring because you are using "curly quotes" instead of standard ASCII quotation marks.
You'll want to replace the “ and ” with ". Just use find and replace in your text editor.
Any number of issues can cause the error you are seeing:
test.cgi
executable (chmod 755) on the server?test.cgi
designated as a ScriptAlias location or have the ExecCGI option enabled (or equivalent if you're not using Apache)?python
in the system PATH
or in the PATH
in the Web server's startup environment?connect()
parameters correct? Is MySQL running on localhost at the default port?SELECT
statement correct?If you're sure that python
is found (test using the simplest possible script or by logging into the Web server if you can and typing which python
) then you can get much better debug output by adding the following to the top of your script just below the shebang:
import cgitb
cgitb.enable()
More details: http://docs.python.org/library/cgitb.html
Additionally, if you have shell access to the Web server, try running python and just typing:
>>> import MySQLdb
If the command returns with no error, you have your answer for #4 above. If an error is printed, you will need to get MySQLdb installed into the Web server's Python installation.
EDIT: Looking more closely at the top of your question, I see that the code was scraped from an illustrative example at the very beginning of the Django Book. As such, I might expand #5 above to include the caveat that, of course, the requisite database, tables, user, and permissions need to be set up on the MySQL installation available to the Web server.