2015-02-06 178 views
0

您好我是新來使用python與網絡程序,我試圖讓一個使用CSS樣式表一個基本的網站。我有三個文件:app.py,index.html和style.css。他們都在同一個目錄中。當我運行app.py並轉到localhost:8080時,它顯示「Hello World!」,但它沒有來自style.css文件的樣式,並且我的終端顯示「HTTP/1.1 GET /style.css」 - 404 Not Found 。但是,當我在不使用app.py文件的情況下以chrome打開我的index.html文件時,它確實具有樣式格式。任何幫助?提前致謝。我的代碼如下:Python中沒有找到CSS文件

app.py:

import web 

urls = (
    '/', 'Index' 
) 

app = web.application(urls, globals()) 

web.config.debug = True 

class Index(object): 

    def __init__(self): 
     self.render = web.template.render('.') 

    def GET(self): 
     return self.render.index() 

if __name__ == '__main__': 
    app.run() 

的index.html:

<!DOCTYPE html> 
<html> 
    <head> 
     <link type="text/css" rel="stylesheet" href="style.css" /> 
     <title>Basic Web Project</title> 
    </head> 
    <body> 
     <p>Hello World!</p> 
    </body> 
</html> 

的style.css:

p { 
    color: green; 
    font-size: 22px; 
} 

回答

0

當你指定<link type="text/css" rel="stylesheet" href="style.css" />你到你的網頁瀏覽器說以下的事情:在style.css文件是在同一級別的index.html

讓我給你,例如:

/app 
    index.html 
    style.css 

如果你從你的瀏覽器中打開index.html你去到以下網址

file://some/directory/app/index.html 

)這是一樣的file://some/directory/app/因爲瀏覽器在顯示網頁時將始終搜索索引) 以及在此index.html中瀏覽器找到您指定的<link>時,它將在以下URL中搜索該style.cssfile://some/directory/app/style.css 並且當然會發現該文件。

現在有趣的部分。

當您打開localhost:8080它將顯示localhost:8080/index.html這工作,因爲你的web應用程序(即您運行Python腳本)知道,當有人進入該網址做什麼(因爲你在urls變量定義它,你創建了class

但是,當在此頁面上瀏覽器找到<link>標籤,他試圖去localhost:8080/style.css,您的Web應用程序不知道如何處理,因爲您沒有在您的應用程序中指定它。

現在的解決方案: 您必須定義一個網址爲/style.cssclass,它將爲您呈現該網頁。

+0

工作正常!謝謝! – jkesh 2015-02-06 18:14:36

0

你有沒有嘗試添加style.cssurls,您的應用程序對/style.css獲取請求一無所知,可能這就是爲什麼它返回404