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 serve
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 test.py
to a cgi-bin
or htbin
directory and use the following script:
cgiserver.py:
#!/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)
server.serve_forever()
cgi-bin/test.py:
#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')
You should end up with:
|- cgiserver.py
|- cgi-bin/
` test.py
Run with python3 cgiserver.py
and send requests to localhost:8123/cgi-bin/test.py
. Cheers.
You can use a simpler approach and use the --cgi
option launching the python3 version of http server:
python3 -m http.server --cgi
as pointed out by the command:
python3 -m http.server --help
Have you tried using Flask? It's a lightweight server library that makes this really easy.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<title>Hello World</title>'
if __name__ == '__main__':
app.run(debug=True)
The return value, in this case <title>Hello World</title>
, is rendered has HTML. You can also use HTML template files for more complex pages.
Here's a good, short, youtube tutorial that explains it better.