1、使用绝对路径,实例如下:
Python Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# -*- coding: utf-8 -*- #!/usr/bin/python # filename: start_webserver.py # codedtime: 2014-9-6 21:16:39 import bottle #返回一个静态文件 @bottle.route( '/') def help(): return bottle.static_file( 'index.html', root= 'D:/Web_Dev/NewSystem/Web') #注意Root路径的写法 #举例:http://localhost:8089/static/index.html @bottle.route( '/Web/<filename:path>') def index_w(filename): return bottle.static_file(filename, root= 'D:/Web_Dev/NewSystem/Web') #注意Root路径的写法 #举例:http://localhost:8083/static/coach.jpg @bottle.route( '/static/<filename:path>') def send_static(filename): #return static_file(filename, root='/../path/to/static') #此方法不可行 return bottle.static_file(filename, root= 'D:/Web_Dev/NewSystem/path/to/static') bottle.run(host= 'localhost', port= 8018, debug= True) |
这里注意bottle.static_file 函数的root,用的是绝对路径,如果这个地方直接使用相对路径,是不可行的。但绝对路径的使用各移植系统带来了不便,所以这里我们进行相应的转换操作,将相对路径装换为绝对路径,但使用我们依然使用相对路径:
2、方法2使用相对路径,代码如下:
Python Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import bottle
bottle.TEMPLATE_PATH. insert( 0, "./templates/") # 加载templates路径 bottle.TEMPLATE_PATH. insert( 0, "./web_bin/") # 加载web_bin路径 @bottle.route( '/') def index(): return bottle.redirect( './templates/index.html') #重定向到首页(可以 ) @bottle.route( '/web_bin/<filename:path>') def download(filename): return bottle.static_file(filename, root= './web_bin') #相对路径 #templates目录 @bottle.route( '/templates/<filename:path>') def login(filename): return bottle.static_file(filename, root= "./templates/") #相对路径 bottle.run(host= 'localhost', port= 8028, debug= True) |
输入:http://localhost:8084/web_bin/lounge.html 效果如下:
3、 改进的将相对路径转化为绝对路径:
Python Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import bottle
from os.path import abspath, dirname, join #指定的模板路径 CUSTOM_TPL_PATH = abspath( join(dirname(__file__), "templates/")) #静态文件 WEB_Bin_PATH = abspath( join(dirname(__file__), "web_bin/")) bottle.TEMPLATE_PATH. insert( 0, CUSTOM_TPL_PATH) # 加载templates路径 bottle.TEMPLATE_PATH. insert( 0, WEB_Bin_PATH) # 加载web_bin路径 @bottle.route( '/') def index(): return bottle.redirect( './templates/index.html') #重定向到首页(可以 ) @bottle.route( '/web_bin/<filename:path>') def download(filename): return bottle.static_file(filename, root=WEB_Bin_PATH) #绝对路径 #templates目录 @bottle.route( '/templates/<filename:path>') def login(filename): return bottle.static_file(filename, root=CUSTOM_TPL_PATH) #绝对路径 bottle.run(host= 'localhost', port= 8028, debug= True) |