python - 如何在 python http.server 中同时提供文件夹和处理 POST 请求

标签 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 脚本。我曾经在 ./cgi-bin 中有一个 logger.py 并让客户端发送 POST 请求到 http://hostname:8080/cgi-bin/logger.py。并使用 python -m http.server --cgi 8080

调用服务器

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

最佳答案

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

#!/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()

关于python - 如何在 python http.server 中同时提供文件夹和处理 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313034/

相关文章:

python - Twython 的 Twitter 限制为 140 个字符

python - 输入适用于 sklearn.linear 和 sklearn.ensemble 中的某些 sklearn 模型,但不适用于其他模型

python - 如何让命令 python filename.py 工作?

python - 使用 Google App Engine 上的 SetupTools 动态下载和安装 python 模块

python - NoneType 类是否继承对象类?

string - Python 硬编码字符串与 str() 方法之间的差异

python - 为什么这个函数在没有调用return的情况下却有返回值?

forms - 以编程方式发布表单并没有执行我的浏览器正在执行的操作。为什么?

php - 处理适用性声明 2 (AS2) 请求

PHP 文件获取 URL 内容返回 getaddrinfo 失败