user1731699 user1731699 - 1 year ago 114
Python Question

How to execute python script on the BaseHTTPSERVER created by python?

I have simply created a python server with :

python -m SimpleHTTPServer

I had a .htaccess (I don't know if it is usefull with python server)

AddHandler cgi-script .py
Options +ExecCGI

Now I am writing a simple python script :

import cgitb
print 'Content-type: text/html'
print '''
<title>My website</title>
<p>Here I am</p>

I make (name of my script) an executed file with:

chmod +x

I am launching in firefox with this addres: (http : //)

Problem, the script is not executed... I see the code in the web page...
And server error is:

localhost - - [25/Oct/2012 10:47:12] "GET / HTTP/1.1" 200 -
localhost - - [25/Oct/2012 10:47:13] code 404, message File not found
localhost - - [25/Oct/2012 10:47:13] "GET /favicon.ico HTTP/1.1" 404 -

How can I manage the execution of python code simply? Is it possible to write in a python server to execute the python script like with something like that:

import BaseHTTPServer
import CGIHTTPServer
httpd = BaseHTTPServer.HTTPServer(\
('localhost', 8123), \
###  here some code to say, hey please execute python script on the webserver... ;-)

Or something else...

Answer Source

You are on the right track with CGIHTTPRequestHandler, as .htaccess files mean nothing to the the built-in http server. There is a CGIHTTPRequestHandler.cgi_directories variable that specifies the directories under which an executable file is considered a cgi script (here is the check itself). You should consider moving to a cgi-bin or htbin directory and use the following script:

#!/usr/bin/env python3

from http.server import CGIHTTPRequestHandler, HTTPServer

handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi-bin', '/htbin']  # this is the default
server = HTTPServer(('localhost', 8123), handler)


#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')

You should end up with:

|- cgi-bin/

Run with python3 and send requests to localhost:8123/cgi-bin/ Cheers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download