Python CGI checklist: Difference between revisions

From XPUB & Lens-Based wiki
Line 14: Line 14:
''not''
''not''


  file://Users/YOURUSERNAME/Sites/script.cgi
  file:///this/can't/be/right/script.cgi


And if this doesn't work, make sure your webserver is running (Mac OS X: System Preferences, Sharing, Personal Web Sharing should be switched on).
And if this doesn't work, make sure your webserver is running (Mac OS X: System Preferences, Sharing, Personal Web Sharing should be switched on).

Revision as of 12:24, 13 May 2013

InternalServerErrorNegate.png

"Internal server error" got you down... no problem, just check the following

Save the file with the extension ".cgi"

View through HTTP/a web server

If you're seeing the actual source code of the script, you need to make sure that you are viewing the script via a webserver (not just opening the script directly as a file). In other words, the URL should start with "http:" not "file:".

http://localhost/cgi-bin/script.cgi
http://pzwart3.wdka.hro.nl/~YOU/cgi-bin/script.cgi

not

file:///this/can't/be/right/script.cgi

And if this doesn't work, make sure your webserver is running (Mac OS X: System Preferences, Sharing, Personal Web Sharing should be switched on).

She-Bang!

First line of the file should be the "shebang" telling the system (Apache) how to run the script (in other words which language it is).

#!/usr/bin/python

Alternatively you could use the "env" trick + specify a text encoding (in case your code has special characters in it)

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

Permissions must be set to "world-executable"

 chmod +x myscript.cgi

or

 chmod 755 myscript.cgi

See python errors in the browser

Once the script is actually running, there might of course be something wrong in the code of the program itself. By default, if a python exception occurs, you will see either an Internal Server Error or (worse) a blank page. The cgitb module (CGI Trackback) will make python errors appear, and even format them for a browser.

import cgitb; cgitb.enable()

Print the Content-type first!

The very first output of your script must be the "HTTP headers", which at the very least should be a Content-type (with optional character set) followed by a blank line.

print "Content-type: text/html;charset=utf-8"
print

Check the webserver's error log

tail /var/log/apache2/error_log

or maybe..

tail /var/log/httpd/error_log