BottlePy - Serve Static Files From Root Directory

33 Views Asked by At

My filetree looks something like so

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

I know I can make a route point to that directory https://site/public/static-file-1.example but I'd like to have to url like this https://site/static-file-1.example

I managed to achieve this like so

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

But the problem here is that it overrides my other routes. Like if I type in https://site/blog it looks for that file instead of using the blog route.

1

There are 1 best solutions below

0
furas On BEST ANSWER

First create @app.get('/blog') and later @app.get('/<filepath:path>')
and it will find @app.get('/blog') as first matching route for http://site/blog
and it will use correct function for 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)