如何使用 python http.server 将 CSS 样式添加到 HTML 文件?

我有一个从 python 运行的简单 http 服务器,它返回一个 HTML 文件作为 GET 请求。HTMl 文件只有一些输入,并且可以正确发送,但即使链接到 CSS 文件,也没有设置样式。这是服务器.py:


from http.server import BaseHTTPRequestHandler, HTTPServer

import time


hostName = "localhost"

serverPort = 8080


class MyServer(BaseHTTPRequestHandler):

    def do_GET(self):

            self.send_response(200)

            self.send_header("Content-type", "text/html")

            self.end_headers()

            h = open("main.html", "rb")

            self.wfile.write(h.read())

    def do_POST(s):

        if s.path == '/':

            s.path = './main.html'


if __name__ == "__main__":

    webServer = HTTPServer((hostName, serverPort), MyServer)

    print("Server started http://%s:%s" % (hostName, serverPort))


    try:

        webServer.serve_forever()

    except KeyboardInterrupt:

        pass


    webServer.server_close()

    print("Server stopped.")

即使当我托管服务器时,HTMl 文件链接到 output.css,它也会返回没有任何样式的 HTML 文件



繁花如伊
浏览 181回答 4
4回答

交互式爱情

这样做真的很复杂,因为你必须创建新的服务器来服务你的 css 文件。**最好使用强大且流行的解决方案,例如 Flask 和 Django **,您可以在其中轻松配置这些文件。

绝地无双

嘿,我必须自己解决这个问题。您可能已经解决了这个问题,但以防万一其他人偶然发现这个问题,这就是我想出的方法,效果很好!def do_GET(self):    # Cache request    path = self.path    # Validate request path, and set type    if path == "/resources/index.html":        type = "text/html"    elif path == "/resources/script.js":        type = "text/javascript"    elif path == "/resources/style.css":        type = "text/css"    elif path == "/favicon.ico":        path = "/resources/favicon.ico"        type = "image/x-icon"    else:        # Wild-card/default        if not path == "/":            print("UNRECONGIZED REQUEST: ", path)                    path = "/resources/index.html"        type = "text/html"        # Set header with content type    self.send_response(200)    self.send_header("Content-type", type)    self.end_headers()        # Open the file, read bytes, serve    with open(path[1:], 'rb') as file:         self.wfile.write(file.read()) # Send

largeQ

你的html文件或css文件在一个文件夹中吗?如果是这样,请在 html 文件中更改指向“[文件夹名称]/output.css”的链接

慕婉清6462132

当您的 HTML 文件加载到浏览器中时,它会尝试加载 CSS 文件 ( ./output.css)。由于您通过 HTTP 提供此页面,浏览器会发出 HTTP 请求来获取此 output.css 文件,但显然您的服务器不提供此 CSS 文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python