BottlePy - 从根目录提供静态文件

问题描述 投票:0回答:1

我的文件树看起来像这样

root/
├─ etc.../
├─ public/
│  ├─ static-file-1.example
│  ├─ etc...

我知道我可以创建一个指向该目录的路由

https://site/public/static-file-1.example
但我想必须像这样的url
https://site/static-file-1.example

我设法做到了这样

@app.get('/<filepath:path>')  
def server_static(filepath):
    return static_file(filepath, root='./public/')

但这里的问题是它覆盖了我的其他路线。就像如果我输入

https://site/blog
它会查找该文件而不是使用博客路径。

python routes bottle
1个回答
0
投票

首先创建

@app.get('/blog')
,然后创建
@app.get('/<filepath:path>')

它将找到
@app.get('/blog')
作为
http://site/blog

的第一个匹配路线 它将使用正确的函数
http://site/blog

from bottle import Bottle, run, static_file

app = Bottle()

@app.get('/blog')
def hello():
    print('[DEBUG] blog')
    return "Hello World!"

@app.get('/<filepath:path>')  
def server_static(filepath):
    print('[DEBUG] static:', filepath)
    return static_file(filepath, root='./public/')
    
run(app, host='localhost', port=8080)
© www.soinside.com 2019 - 2024. All rights reserved.