Python http.server CGI

时间:2018-05-22 01:51:29

标签: python python-3.x http cgi

需要从本地python服务器运行带有CGI选项的python scrips

目前在我的Apache上,我使用CGI来获取任何人对我的python脚本所做的所有get和post请求,告诉他们做事。

例如,如果我向127.0.0.1:8080?filename=yomomma发出get请求 我的python脚本应该打印' yomomma'

#!/usr/bin/python3

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

继承服务器我在python中运行(我不知道我在做什么)

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()

我希望能够在任何python文件中指出这个并获取该python文件来读取CGI参数

1 个答案:

答案 0 :(得分:0)

不清楚您要在这里做什么。

如果您只想在HTTPServer上运行CGI脚本,那非常简单。 CGIHTTPRequestHandler并非要子类化,这是您已经完成的工作,并且您无需重写do_X函数。它只是返回CGI脚本的输出,就像其他服务器一样, if 在cgi_directories文件夹下。阅读this

因此在主函数中,您将具有:

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

然后只需正常调用CGI脚本即可:

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

如果要使用http.server来处理请求,则需要使用BaseHTTPRequestHandler,而不是CGIHTTPRequestHandler。然后获取表单数据略有不同,但很容易。阅读“ HTTP POST”下的this部分