为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁花如伊 2023-09-12 19:51:26
我有一个从 python 运行的简单 http 服务器,它返回一个 HTML 文件作为 GET 请求。HTMl 文件只有一些输入,并且可以正确发送,但即使链接到 CSS 文件,也没有设置样式。这是服务器.py:from http.server import BaseHTTPRequestHandler, HTTPServerimport timehostName = "localhost"serverPort = 8080class 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 文件
查看完整描述

4 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

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


查看完整回答
反对 回复 2023-09-12
?
绝地无双

TA贡献1946条经验 获得超4个赞

嘿,我必须自己解决这个问题。您可能已经解决了这个问题,但以防万一其他人偶然发现这个问题,这就是我想出的方法,效果很好!


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


查看完整回答
反对 回复 2023-09-12
?
largeQ

TA贡献2039条经验 获得超7个赞

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



查看完整回答
反对 回复 2023-09-12
?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

当您的 HTML 文件加载到浏览器中时,它会尝试加载 CSS 文件 ( ./output.css)。由于您通过 HTTP 提供此页面,浏览器会发出 HTTP 请求来获取此 output.css 文件,但显然您的服务器不提供此 CSS 文件。



查看完整回答
反对 回复 2023-09-12
  • 4 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信