Run Python scripts inside Apache.
Note: You must already have Apache and Python installed on Windows.
Step 1: Configuration
Go to C:\Apache24\conf and open the httpd.conf file in a text editor (such as Notepad). Find the following line:
Options Indexes FollowSymLinks
Add ‘ExecCGI’ to the end so that it looks like this:
Options Indexes FollowSymLinks ExecCGI
Next, find this line:
#AddHandler cgi-script .cgi
Uncomment it by removing the hashtag and add .py to the end:
AddHandler cgi-script .cgi .py
Step 2: Creating a Python file
#!C:\Python34\python.exe import time current_time = time.strftime("%H:%M:%S") print( """Content-type: text/html <h1>Welcome! This page was made with Python!</h1> <h2 style="color:green;">The time is currently """ + current_time + "</h2>")
Here’s a quick runthrough:
#!C:\Python34\python.exe
simply tells Apache where to find the Python executable. This must be correct. Change it if you have installed Python in another location.
time.strftime()
is a piece of python code that tells you what the time and/or date is.
Content-type: text/html
must be the first thing printed and must be followed by an empty line.
<h1>
and <h2>
are html tags that make different sized headers.
Save your file to C:\Apache24\htdocs as time.py
Part 3: Testing
Now start Apache from CMD by typing in C:\Apache24\bin\httpd.exe
Then go to http:\\localhost\time.py and see your Python script in action! Now you can try creating your own script.
Troubleshooting
Internal Server Error: Go to C:\Apache24\logs and open error.txt . Check the latest log for one of the following errors:
Bad file descriptor: Couldn’t create child process – Ensure that the first line #!C:\Python34\python.exe
is set to the right location, the location of your python.exe file.
Malformed header from script ‘time.py’ – Ensure that you have included the line Content-type: text/html
and an empty line afterwards.
Python errors such as SyntaxError and ValueError will also cause an internal server error and will be logged in error.txt