【问题标题】:Simple HTTP server in Python. How to GET files from DIR_PATH?Python 中的简单 HTTP 服务器。如何从 DIR_PATH 获取文件?
【发布时间】:2018-07-05 10:59:58
【问题描述】:

我有这样的代码用于在 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】:

    似乎我发现了问题。

    它不起作用,因为:

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

    这里是固定行:

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

    str(self.path)[1:]self.path 字符串中删除第一个符号 (/)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2020-12-03
      • 1970-01-01
      相关资源
      最近更新 更多