Python中的简单HTTP服务器。如何从DIR_PATH获取文件?

问题描述 投票:0回答:1

我有这样的代码用于在Python 3上运行简单的服务器。我知道我可以使用像这样的python -m http.server 8080,但是我想了解它是如何工作的并且为服务文件扩展设置限制。

我尝试使用path.join(DIR_PATH, self.path),但似乎不起作用。

>> FileNotFoundError: [WinError 2]: 'c:/test.html'

DIR_PATH = 'C:\script_path\src\'但它适用于/请求的路径和服务器打开index.html

因此,path.join(DIR_PATH, 'index.html')是作品。

from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path

DIR_PATH = path.abspath(path.dirname(__file__))

hostName = "localhost"
hostPort = 8080


class RequestHandler(BaseHTTPRequestHandler):

    content_type = 'text/html'

    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-Type', self.content_type)
        self.send_header('Content-Length', path.getsize(self.getPath()))
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(self.getContent(self.getPath()))

    def getPath(self):
        if self.path == '/':
            content_path = path.join(DIR_PATH, 'index.html')
        else:
            content_path = path.join(DIR_PATH, self.path)
        return content_path

    def getContent(self, content_path):
        with open(content_path, mode='r', encoding='utf-8') as f:
            content = f.read()
        return bytes(content, 'utf-8')

myServer = HTTPServer((hostName, hostPort), RequestHandler)
myServer.serve_forever()
python-3.x httpserver simplehttpserver
1个回答
0
投票

似乎我发现了问题。

它不起作用,因为:

self.path在字符串中有/符号,而path.join在Windows中找不到文件。

这是固定行:

content_path = path.join(DIR_PATH, str(self.path)[1:])

qazxsw poi从qazxsw poi字符串中删除第一个符号(qazxsw poi)。

© www.soinside.com 2019 - 2024. All rights reserved.