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

前端 未结 3 393
抹茶落季
抹茶落季 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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('Hello World')
    

    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.

提交回复
热议问题