如何在python http.server

时间:2019-10-09 22:20:00

标签: python python-3.x http https

我正在运行使用以下代码提供当前目录的https服务器。

#!/usr/bin/env python3

from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl

httpd = HTTPServer(('hostname', 8443), SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="/Users/test/Desktop/key.pem", certfile="/Users/test/Desktop/cert.pem", server_side=True)
httpd.serve_forever()

我还希望服务器能够处理带有某些值的POST请求。我想记录任何以POST形式发送到文件的内容。以前,我为此目的使用cgi脚本。我以前在logger.py中有一个./cgi-bin,并使客户端将POST请求发送到http://hostname:8080/cgi-bin/logger.py。并使用python -m http.server --cgi 8080

调用了服务器

但是,由于我需要通过https服务,因此我不再从命令行调用http.server,而是使用上述脚本。我不知道可以处理POST请求而不会破坏提供文件夹中内容的通常功能。

1 个答案:

答案 0 :(得分:1)

通过更多的谷歌搜索,我使用下面的代码解决了该问题。

#!/usr/bin/env python3

from http.server import HTTPServer, SimpleHTTPRequestHandler
from io import BytesIO
from sys import argv
import ssl


class requestHandler(SimpleHTTPRequestHandler):
    def do_POST(self):

        #Doing things with incoming POST data
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        body = self.rfile.read(content_length) # <--- Gets the data itself
        bodydata = body.decode('utf-8')
        logdata = "\n"+bodydata+"\n"
        logfile = open('log.txt', 'a+')
        logfile.write(logdata)
        logfile.close()

        # Crafting the response to be sent back to client

        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(b'\nA POST request with some data was recieved\n')
        response.write(b'The recieved data shall be logged\n')
        self.wfile.write(response.getvalue())

portstr = argv[1]
port = int(portstr)
keyloc = "/Users/test/Desktop/key.pem"
certloc = "/Users/test/Desktop/cert.pem"

httpd = HTTPServer(('localhost', port), requestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile=keyloc, certfile=certloc, server_side=True)
httpd.serve_forever()