scre_www scre_www - 1 year ago 90
Python Question

How to load static files in python bottle in URL's

I'm working on a python app in Python Bottle. The app works fine if I'm on 1 lvl deep URLs like /dashboard or /rules or /page. However, if I go deeper like /dashboard/overview or /rules/ruleone or /page/test the CSS, JS, fonts and images will fail. :(

The HTML source code still poinsts to /assets/ but if I'm on an URL like /rules/ruleone, the right path should be something like ../assets or ./assets right? The path /assets/ only works on the first level but not on deeper lvls, in other words: bottle doesnt adapt the static file path to the current directory. How do I fix this?

I'm stuck on this problem for days now, I realy hope someone can help me. :(

My code (simplified):

#!/usr/bin/env python
import lib.bottle as bottle
from lib.bottle import route, template, debug, static_file, TEMPLATE_PATH, error, auth_basic, get, post, request, response, run, view, redirect, SimpleTemplate, HTTPError, abort
import os, sys, re

def show__page_dashboard():
return dict(page = 'Dashboard')

def show_page_rules_more(rule):
return dict(page = rule)

def server_static(filepath):
return static_file(filepath, root='/var/myapp/assets')

TEMPLATE_PATH.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "view")))

from lib.bottledaemon import daemon_run
if __name__ == "__main__":

So my app runs in daemon mode. The structure is:





  • css

  • js

  • ...


  • secure_page.tpl

  • footer.tpl

  • header.tpl

  • ...

I hope someone can help me out on this, thanks in advance guys, I love u! <3

Answer Source

Alright I found the solution for my problem. Bottle offers an URL tag to dynamicly build URLs.

from bottle import url

def show__page_dashboard():
    return dict(page='Dashboard', url=url)

@route('/assets/<filepath:path>', name='assets')
def server_static(filepath):
    return static_file(filepath, root='/var/myapp/assets')

This is how I load my CSS/JS/images

<link href="{{ url('assets', filepath='css/style.css') }}" rel="stylesheet" type="text/css"/>

Dynamic menu URL's (in the navigation for example) is done this way:

{{ url('/dashboard') }}

I hope this info will help someone who is strugling with the same problem as I was.

Tested on v0.12 and v0.13dev

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download