#!/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!"
My goal is to replace PHP with Python. I’m pretty good with PHP and I can use Python on my own local machine, but I can’t get it to work on my web server. My web host says they support Python, so I must be doing something wrong.
Now, Python is associated with CGI. Do python files have to go into my cgi-bin folder? I’ve never seen a web file with a py extension or a cgi extension, I don’t know how these things work, I’m really only familiar with PHP.
I watched the first hour of Google’s “Learn Python” class and that only talks about running Python locally.
🙁 Sorry I’m so nub, please fix me.
That’s a perfectly acceptable CGI script. If you are using Apache, it will need to go into your cgi-bin, need to be executable (I may be wrong on this), and you should name it with the common extension for the language
.py, or with.cgi.If you can control what files your webserver will consider CGI, you can place the file wherever you want. Chances are, you can’t control that. You can view more information on CGI in Apache here: http://httpd.apache.org/docs/2.2/howto/cgi.html
The basic gist is that Apache will not treat a file as a CGI file unless two conditions are met: The
cgi-scriptwill need to be activated using theAddHandlerorSetHandlerdirectives, andExecCGIwill need to be enabled in theOptionsdirective. Typically, this is not available to the user in a shared hosting environment.EDIT: To clarify, CGI is just a mechanism for you to write scripts in any arbitrary language, and have your webserver execute them and send the output from that script to your clients. It’s not a recommended approach for anything but a simple script, due to the fact that on every single request the server will fire up a new instance of your interpreter. For Python, the best solution would be a WSGI compatible framework, such as Flask, Bottle, or Django. The first two are micro-frameworks that try to stay out of your way, while Django is a full-stack framework that provides a whole lot of glue.