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

前端 未结 3 382
抹茶落季
抹茶落季 2020-12-16 08:43

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

相关标签:
3条回答
  • 2020-12-16 09:20

    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.

    0 讨论(0)
  • 2020-12-16 09:21

    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
    
    0 讨论(0)
  • 2020-12-16 09:23

    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.

    0 讨论(0)
提交回复
热议问题