亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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條經驗 獲得超8個贊

你的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 關注
  • 217 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號