How to execute python script on the BaseHTTPSERVER

2019-01-26 00:03发布

问题:

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) with:

AddHandler cgi-script .py
Options +ExecCGI

Now I am writing a simple python script :

#!/usr/bin/python
import cgitb
cgitb.enable()
print 'Content-type: text/html'
print '''
<html>
     <head>
          <title>My website</title>
     </head>
     <body>
          <p>Here I am</p>
     </body>
</html>
'''

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

chmod +x test.py

I am launching in firefox with this addres: (http : //) 0.0.0.0:8000/test.py

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), \
CGIHTTPServer.CGIHTTPRequestHandler)
###  here some code to say, hey please execute python script on the webserver... ;-)
httpd.serve_forever()

Or something else...

回答1:

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.



回答2:

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.