2014-02-17 22 views
4

所以我有一個瓶子web框架運行,但我想有一個網頁。如何在瓶子服務器中返回一個html文件?

我已經在html和css中創建了網頁,但我不知道如何讓瓶子使用它。 我有它只顯示HTML但它的CSS部分不起作用。

我試過Google搜索,但我似乎無法找到一個這樣的例子。

@get('/test') 
def test(): 
    return static_file('index.html' , root="views") 

我的css文件和views文件夾在同一個目錄下。

+0

你說起那瓶框架? – IanAuld

+0

是的,我會將其添加到主要問題 – Ramis

回答

6
from bottle import static_file 
@route('/static/<filename>') 
def server_static(filename): 
    return static_file(filename, root='/path/to/your/static/files') 

這是Bottle文檔爲靜態文件提供服務的代碼。

+0

我知道如何做到這一點,它返回我的HTML,它工作正常,但我的CSS不起作用。這是我主要關心的問題。 – Ramis

+0

@Ramis您的.css文件是否也在同一個目錄中?發佈你用來調用'static_file()'的代碼和文件夾層次結構的描述可以更容易地進行調試。 – unholysampler

+0

已添加到原文 – Ramis

-1

Bottle最適合API,其中路由不返回HTML文件。但是,您可以使用static_file函數提供靜態HTML文件。

如果您正在尋找一個更全面的HTML模板框架,請嘗試Flask

+0

是的,這是我在開始時選擇瓶子的原因,但現在我需要一個帶有API的網頁。我沒有時間去改變Web框架。 – Ramis

0

如果我們爲所有項目中的常規情況下的js和css文件(在html文件中使用)有不同的文件夾,我們需要分別明確地提供js和css目錄內容。

參考下面的代碼爲進一步的細節:

from bottle import route 
from bottle import static_file 

#Hosts html file which will be invoked from browser. 
@route('/filesPath/<staticFile>') 
def serve_static_file(staticFile): 
    filePath = '/path/to/your/static/file/' 
    return static_file(staticFile, filePath) 

#host css files which will be invoked implicitly by your html files. 
@route('/files_path/css/<cssFile>') 
def serve_css_files(cssFile): 
    filePath = '/path/to/your/css/file/' 
    return static_file(cssFile, filePath) 

# host js files which will be invoked implicitly by your html files. 
@route('/files_path/js/<jsFile>') 
def serve_js_files(jsFile): 
    filePath = '/path/to/your/jss/file/' 
    return static_file(jsFile, filePath) 
相關問題