NoteMe

- by Øyvind Østlund

Running Python as CGI in Apache in Windows:

, , ,

There is not many domains out there today which holds only static pages anymore. These days Python is my language of choice when it comes to dynamic pages, and here is my first help to those who wants to try it out.

Why CGI? And why, really why Windows?!?
You have basically two different choices when it comes to run Python code to create dynamic pages. You can run it as a mod, which is by far the preferred choice both when it comes to speed and ease of handling. If you have the possibility to install mod_python on your server, or if it is already installed, I suggest you stop reading right away, and do just that.

The reason I write this is not because it is the preferred way, but because at most web hosts you don't have the possibility to install mod_python, and very few web hosts have it pre installed for you. But your problems won't stop there. Most tutorials will only show you how to use mod_python, and leave you to figure out how to do the CGI part. So that is what I will try to do something about now. In Linux, setting up Apache to run Python as CGI is just as difficult as to just find out where Python is installed and you are ready to go, but for Windows users, you can google your self to death, or keep reading.

Prerequisites:
This is no tutorial for setting up your whole development server. I assume you know how to set up your Apache server on your own in Windows. After all, it is more or less just to press the install button. But if you don't know, and you are willing to learn, here is a link to a tutorial a good friend of mine wrote a while ago. It should get you going up and running in no time, and add some basic security for you as well for your development machine.

The same goes for Python. Just install it. There is no more fuzz about it. After it install, and you have tested that it will work, you are ready to move on to start using it for your server.

Running Python on Apache as CGI:
In Linux you are probably used to the shebang line which tells the script where Python is to be found, so it can run the script for you. There is an equal way of doing it in Windows, but there is a smarter way.

Well, if it is smarter is still discussed, and probably will be forever, but the good part about it, is that it makes it easy to upload the script to a Linux server, without any changes and it will still run. If you leave the Linux shebang line there, you can make Apache ignore it on your Windows server, and it will still be read when you use the script on your Linux server.

The way you do it, is to edit the http.conf file of yours. Go to:

Start Menu -> Programs -> Apache HTTP Server -> Configure Apache Server -> Edit the httpd.conf Configuration File

And locate the line that looks like:

#ScriptInterpreterSource Registry

Remove the comment (#) , and there you go. Now windows will use the registry to find out where Python is installed, and you have all read read past the part where I asked you to check if you could run Python script, so that's really it.

But you are not done just yet Mr. Even though Apache now is aware of Python, there is still a missing link between your Python scripts and Apache. You need to tell Apache what file types you are using for Python. The most usual file type is .py, but anything goes. But using .py is a good start. So scroll down on to the bottom of your httpd.conf file, and add the line:

AddHandler cgi-script .py

This tells Apache that it should handle all .py files as CGI scripts. And that's what we are after. You can add more space separated file types after the .py, without me seeing the point in doing that here.

So this is it?
Yeah, that's basically it. But there is one more thing we should go through. Safety is a big concern when you are setting up a server. And Apache is usually set up to not allow CGI scripts to run outside the cgi_bin files. If this is ok for you, then you are done. If you are like me, you want a bit more freedom. You can easily give access to run Python scripts in all folders on your server. The easiest way, is again to edit your httpd.conf file. Find a line that looks something like:

Options Indexes FollowSymLinks

There might be a few other words added to it, or less, but it should be between the <Directory> tags pointing to your root folder. At the end add ExecCGI, which basically permits Apache to execute CGI scripts, and if you did write it in your root <Directory>, it will automatically give Apache access to run it in all sub directories as well. This is both great freedom for you, but also for hackers if they find holes in your scripts they are able to take advantage of. So be warned. For this approach, FastCGI might be a safer bet, but again you have the problem with it not being installed on too many servers around the world. But maybe I will find the time to write up a little something about that later on.

Your first dynamic page with Python on Windows:
So you are ready to test it all out. Writing a python cgi script is a little bit different than a normal python script, because this time what you print out has to be a web page. Usually it will be in HTML or XHTML format, but you also have to remember to print out the correct content-type as well as a minimum. So a minimal Python CGI script might look like something like this:

print "Content-type: text/html"
print
print "<html><head>"
print "Hello World"
print "</head><body>"
print "Thanks NoteMe for teaching me this."
print "</body></html>"

Even though I left out the DocType with more on purpose, it should give you an idea about what it should look like. Try now to save this to a file called test.py in the root of your Apache server on your machine. On my machine that would be:

C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\

Then point your browser to:

http://localhost/test.py

if you chose port 80 when you installed Apache. If you chose something else like 8080, then the port number has to be added after the domain name like this:

http://localhost:8080/test.py

If you still have problems, don't hesitate to ask. I usually always answer no matter if I have an answer or not when I have time to do so.


- Øyvind Østlund -

Blog tag: 5 things I’d like to see in OperaSyntaxError: from __future__ imports in Cheetah

Comments

Janizomg Thursday, August 30, 2007 5:43:43 AM

Nice. I really need to give Python CGI programming a shot sometime. It's such a good and easy to use language. Dunno if it can beat PHP though, at least when I'm not used to doing stuff in Python as much as in PHP.

Øyvind ØstlundNoteMe Thursday, August 30, 2007 7:07:54 AM

You will get used to it fast. And Python has so many more uses than PHP altogheter. But if you have the posebility to use mod_python I would suggest to use that for web programming over CGI.


- ØØ -

Rudi VisseriGod Saturday, September 8, 2007 2:25:58 PM

PHP all the way for web applications!! bigsmile

Øyvind ØstlundNoteMe Saturday, September 8, 2007 3:11:51 PM

Rude Rudi p You are just saying that to tick me off p PHP is nice. Just not perfect for every occasion wink


- ØØ -

Rudi VisseriGod Saturday, September 8, 2007 5:16:00 PM

p You know I love you!! love

But really PHP is always the best for web applications, until we write our own language of course Øyvind! heart

Unregistered user Monday, November 12, 2007 3:50:02 AM

beastin writes: Thanks for putting together this page. It really helped me get Apache running for local Python CGI scripting.

Unregistered user Tuesday, November 20, 2007 12:00:58 AM

Bill writes: Say I had a program written in Python that needs to interface with a MySQL database on a shared hosting system (netfirms). They "do not have plans" to add MySQLpython to their service so I can connect to the Db. Is there: A) a program to translate my python program elements to cgi; or B) install a script at my site level that will enable connection to the MySQL database? Thanks - sincerely - for any help anyone out there can provide.

Øyvind ØstlundNoteMe Tuesday, November 20, 2007 12:18:14 AM

Do you have SSH access to your server? That's what I did with my server (at dreamhost.com). I SSHed to the server, used wget to download the tarball, then installed it on my own. It doesn't have to be installed for all users on a shared hosting for you to take advantage of it.

You could also access MySQL directly with Python, but it's not meant to be used like that, so it's hard to find any information at all on how to do that.


- ØØ -

Unregistered user Wednesday, November 21, 2007 2:10:12 PM

Bill writes: I do indeed, but sadly I have no idea how to do what you are suggesting. It ain't easy being a knucklehead. Would I just SSH into my account and upload the MySQLpython into my cgi-bin or something? I appreciate your time and guidance. Bill

Øyvind ØstlundNoteMe Friday, November 23, 2007 7:44:34 PM

Well, I am no expert, but from the top of my head, try something like this:

- Log on to your server and go to your home directory.
- Then set up your environment. Write:
export LD_LIBRARY_PATH=$HOME/lib/
export PATH="$HOME/bin:$PATH"
source ~/.bash_profile
- Then to download and install. Write:
wget http://downloads.sourceforge.net/mysql-python/MySQL-python-1.2.2.tar.gz
tar -xzvf MySQL-python-1.2.2.tar.gz
cd MySQL-python-1.2.2
python setup.py build
python setup.py install


Hope it works. If not you could always try to ask again, but my best bet is your support at your hosting company.


- ØØ -

Unregistered user Saturday, December 15, 2007 3:02:30 AM

tag writes: Thank you for this wonderful article. It would be nice to remind the readers to replace any "./Script.py" to just "Script.py" in windows. Correct me if I'm wrong

Øyvind ØstlundNoteMe Saturday, December 15, 2007 5:04:19 PM

You are not wrong. Although the blog post was written in Windows for Windows, so it is correct all over there. If you ment in my comment, then yes. But it would still not work. The whole installation process would be different on a Windows machine.


- ØØ -

Sumitfanna4u_sumit Friday, December 21, 2007 2:53:10 AM

Merry Christmas Øyvind

Unregistered user Tuesday, November 11, 2008 11:02:41 PM

Anonymous writes: For some reason I'm getting an error when I try to access the test script "Forbidden You don't have permission to access /test.py on this server." I've restarted Apache, and my PHP scripts in the same directory are running okay. Any guess as to what's I'm doing wrong? Thanks

Unregistered user Saturday, February 7, 2009 7:09:43 AM

Avinash writes: Hello, I did all the steps listed above,but i am still not able to run the simple python file(I am new to Python). I have made a file named hello.py and the content is print "Hello"; When i run this file,it gives me print "Hello" this OP only rather it should have give me Hello. Thanks

Unregistered user Sunday, April 26, 2009 9:44:31 PM

Simran writes: Really helpful and easy instructions. Fixed my problem to get Python working on Windows and Apache Server :)

Unregistered user Wednesday, October 28, 2009 11:08:28 AM

jurjur writes: Thank you very much 4 your help. I did like this: Options ExecCGI Indexes FollowSymLinks MultiViews SetHandler cgi-script and it worked with : http://localhost/cgi-bin/test.py Thank you very much in deed. Jur jur

Unregistered user Thursday, November 26, 2009 6:22:51 AM

Vivek R writes: Hi, Really good article.All info that I needed got at one place. Also, Can you please let me know how to make the script read files in the same folder in Linux. By default it takes the files under root folder. i.e For Example: if I write in file /var/www/html/trial/index.py info = open('./info.txt','r') It tries to open file under folder '/' as '/info.txt' instead /var/www/html/trial/info.txt It will be of great help to me If you give me solution to work this out. Thanks Vivek R

Unregistered user Sunday, January 31, 2010 4:38:57 PM

Nimetön writes: I tried this python code: #!c:/Python31/python.exe -u print "Content-type: text/html" print print " " print "" print " " print "Hello." print " " However, I just get this error on Windows: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. There wasn't this line "#ScriptInterpreterSource Registry" in httpd.conf at all, but I told the location of Python manually: C:\Python31;. Any easy suggestions?

Unregistered user Sunday, May 16, 2010 7:37:31 PM

Cameron writes: @Nimetön, it looks like you are using python 3.1, but still using python 2.x print statements. Remember, in python 3, print " " will give you an invalid syntax error. It needs to be: print(" ")

Unregistered user Wednesday, June 2, 2010 6:20:29 PM

Kevin writes: Hi, I have a xammp server installed. I installed mod_python in the python directory and located the path to apache. Also I have tested it and its ok. I configured my server as u have mentioned except the fact that I am not able to find #ScriptInterpreterSource Registry in my http.conf file . I am trying to run cgi script still its not giving any html output, it just showing me the script which I tried to execute. Can you suggest me something..

Unregistered user Monday, August 16, 2010 1:42:55 AM

Anonymous writes: I put t1.py which have command in python to read the first name + Second name from the index.html form inside /var/www/ in apatche server after the t1.py read the two inputs it will save them in w1.txt file but I can't rune the t1.py from index.html form

Unregistered user Tuesday, August 17, 2010 11:35:12 AM

shine writes: i used this webpage and was successfullin Running Python as CGI in Apache in Windows but on the internet explorer i got the htnl page but along with "print " statement printed on webpage which is python source code ..... so any solution for tat....... Below is the result on IE webpage for the above program in my system......... print "Content-type:text/html\r\n\r\n" print '' print '' print '' print '' print '' print ' Hello Word! This is my first CGI program ' print '' print ''

Unregistered user Tuesday, August 24, 2010 1:54:45 PM

Fahed writes: Thaaaaaaaaaaaaaaaaaaaaaaaaaaaaanks Peace be upon you

Unregistered user Thursday, September 9, 2010 1:33:44 PM

Song Toan writes: -Put #!python on top of your script and -Ensure that .py is associated with python.exe

Unregistered user Tuesday, October 5, 2010 9:10:56 PM

phpguru writes: Thanks for the post man, it was quite helpful. The thing is, if you're reading this in 2010 like me - you want to change print "" to print("") for Python 3.x + It took me two hours to figure out what this means in apache error log: Premature end of script headers: test.py File "C:\\wamp\\www\\test.py", line 2\r print "Content-type: text/html"\r ^\r SyntaxError: invalid syntax\r And it turns out it has nothing to do with line-endings, it's just breaking the Python interpreter without the parentheses.

Unregistered user Thursday, December 9, 2010 4:03:34 PM

Анонімний writes: Buildings are expensive and not everyone is able to buy it. However, business loans are created to help people in such kind of hard situations.

Unregistered user Friday, April 15, 2011 12:51:45 AM

Anonymous writes: Hi, I get the following error when I execute the script: Forbidden You don't have permission to access /test.py on this server.

TempUserProtempuserpro Friday, April 15, 2011 6:59:57 PM

Hi, I get the following error when I execute the script: Forbidden You don't have permission to access /test.py on this server.

Unregistered user Wednesday, May 25, 2011 3:08:36 AM

Anonymous writes: Sorry for long post but i'm totally new to Python n Apache 2.2. --------------------------------------------------------------- Hello All I'm fairly new in Python 2.7 and using Apache 2.2 running on windows XP. I've installed Apache 10 days ago and installed it in default directory: c:\program files\apache foundation..\apache2.2. I haven't change anything in 'httpd.conf' file and accepted the 'cgi-bin' directory as a default directory to run all .cgi files. I've been reading a lot on how to run cgi on apache and feel so hopeless cuz i've tried so many things but still i can't run .cgi scripts neither from default cgi-bin nor default htdocs . my apache's directory setup it's weird but during installation everything went so smooth without any error at all. but reading through diff forum, the cgi-bin directory must be under web root (htdocs ) but mine after installation is: apache 2.2 > bin > cgi-bin > conf > error > htdocs > icons > logs > manual. when i try to run my python .cgi script(s) from 'htdocs' (using DocumentRoot) as a folder to put my .cgi scripts. (i'm not worry about security risk from running scripts from 'htdocs ' cuz it's for educational purpose n home use only). when i run .cgi script from 'htdocs' i get following error: ------------------- 404 Not Found The requested URL /Hello2.cgi was not found on this server. ---------------------- (the URL i'm using is: http://127.0.0.1/Hello2.cgi or http://localhost/Hello2.cgi (i only have one entry in host file which is: 127.0.0.1 localhost ) when i read the 'error' log is says: ------------------------------------------ [error] [client 127.0.0.1] File does not exist: C:/apache I don't know why it points to this weird directory: c:\apache?? In my 'http.conf' file my settin for 'htdocs' are: ----------------------------------------------------- DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs" Options FollowSymLinks +ExecCGI AllowOverride None Order allow,deny Allow from all AddHandler cgi-script .cgi .pl .py ----------------------------------------------------- when i try to run the same script from default cgi-bin directory which is activated in 'httpd.cof' by default i get following error: 500 Internal Server Error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request..........(didn't want to wast more space) The URL i'm using is: http://127.0.0.1/cgi-bin/Hello2.cgi or localhost/.... the error log says: [client 127.0.0.1] C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/Hello2.cgi is not executable; ensure interpreted scripts have "#!" or "'!" first line. [client 127.0.0.1] (9)Bad file descriptor: don't know how to spawn child process: C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/Hello2.cgi but the Hello2.cgi is like this: ----------------------------------- #!c:/Python27/python.exe -u print "Content-type: text/html\n\n"; print "Hello World! "; print "\n"; ------------------------------------ in the 'http.conf' setting for default 'cgi-bin' is: ScriptAlias /cgi-bin/ "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/" AllowOverride None Options Includes +ExecCGI Order allow,deny Allow from all AddHandler default-handler .html .htm .shtml by default there's index.html in cgi-bin directory which i also copied to 'htdocs' just to make sure it's there. Once i've tried creating 'cgi-bin' under DocumentRoot (htdocs) and copy n pasted all my script there but i get 'an access error'. I don't know what i'm doing wrong? Please help me out to get my python .cgi script running in Apache. I'm so frustrated after reading so many forums (which i've also learn a lot) still not being able to nail down the problem. I can run any .cgi script from command prompt but not from browser. I've also tried to use this in order to eliminated using 'shebang' line which is really making me sick cuz i can't find anything in there. I added this to 'http.conf': ScriptInterpreterSource Registry PassEnv PYTHONPATH SetEnv PYTHONUNBUFFERED 1 still not working. I'm running out of options here. Your help is much appreciated.

Unregistered user Saturday, June 4, 2011 1:24:11 PM

Arjun writes: Here when i execute this script, then it print the script as it is i put the url as http://localhost/test.py then it printed as print "Content-type: text/html" print print "" print "" print "" print "Thanks NoteMe for teaching me this." print "" It is not getting executed

Unregistered user Thursday, June 16, 2011 4:01:34 PM

Anonymous writes: ipage hosting information

Unregistered user Wednesday, November 23, 2011 3:21:42 AM

Anonymous writes: Youll be capable to make a firm cheap ugg boots decision delicate colours some as chestnut or stone dust shades. Every time you favor to liven essential things way up a tad, you can opt for uggs cheap colours this specific as aqua sea, raspberry rose or location blue. You will discover this even metallic shades together as ugg boots canada printed material with floral styles. It doesn¡¯t matter what exactly your model, decide on a colour which you cheap ugg boots sale adore really model which matches your character using your wardrobe cheap ugg boots flawlessly. The Australian UGG boots may be cheap uggs bought in a multitude of heights to hold your own style. You can aquire brief boots called as traditional limited thats all over seven inches through a person's ankle. Plus, there¡¯s tall boots that have been basically two times as cheap ugg boots tall. Until such time as most recently, uggs cheap I did absolutely no strategy there uggs canada was this a massive number of kinds, shades and heights offered. As a result in the versions, it¡¯s possible to be sure to identify the excellent boot to compliment nearly cheap ugg each outfit it¡¯s likely you might have. 742051163fc1f2e1ae1334d01be6a6a22 cheap ugg boots canada uggs cheap uggs tall ireland ugg boot http://www.cheapuggbootslady.com/ cheap uggs sale http://www.uggsbootscanadacheap.net/ cheap uggs canada http://www.cheapuggbootshome.net/ cheap uggs

Unregistered user Friday, December 16, 2011 6:28:48 AM

Anonymous writes: to buy to get new coupon and check coupon code available

Write a comment

New comments have been disabled for this post.