简体   繁体   中英

Python http.server CGI

Need to run python scrips with CGI options from a local python server

At the moment on my Apache I use CGI to get all the get and post requests anyone does to my python scripts to tell them to do things.

For example if I do a get request to 127.0.0.1:8080?filename=yomomma My python script should print 'yomomma'

#!/usr/bin/python3

import cgi, os
form = cgi.FieldStorage()
fileitem = form['filename']
print(fileitem)

Heres the server im running in python (I have no idea what im doing apparently)

from http.server import *
from urllib import parse
import os
import cgi
class GetHandler(CGIHTTPRequestHandler):
    def do_GET(self):
        form = cgi.FieldStorage()
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write('<meta http-equiv="refresh" content=1; URL=http://127.0.0.1:8080" /><pre>'.encode('utf-8'))
        self.wfile.write(str(os.popen('python my_site.py').read()).encode('utf-8'))

if __name__ == '__main__':
    from http.server import HTTPServer
    server = HTTPServer(('localhost', 8080), GetHandler)
    print('Starting server, use <Ctrl-C> to stop')
    server.serve_forever()

Id like to be able to point this at any python file and get that python file to read the CGI parameters

It's unclear what you're asking to do here.

If you just want to run CGI scripts on HTTPServer, that's very simple. CGIHTTPRequestHandler is not meant to be subclassed, which is what you have done, and you don't need to rewrite the do_X functons. It simply returns the output of a CGI script like any other server, if it's under a cgi_directories folder. Read this .

So in the main function, you would have:

server = HTTPServer(('localhost', 8080), CGIHTTPRequestHandler)

Then just call a CGI script normally:

127.0.0.1:8080/cgi-bin/myscript.cgi?filename=yomomma

If you want to utilise http.server to handle requests, you need to use BaseHTTPRequestHandler, not CGIHTTPRequestHandler. Getting form data is then slightly different but easy. Read the section of this under "HTTP POST"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM