Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't reference css stylesheet in template being loaded by python

Tags:

python

bottle

I'm new to using Python and have came across a problem when trying to reference my style-sheet from a .tpl document. My python, template and css documents are all in the same directory however when I load the page using the CMD to "localhost:8080" it shows the template without the style being applied.

In my template document index.tpl i have referenceed three stylesheets:

<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="animate-custom.css" />

And my python file outputs the template: index.py:

from bottle import route,template,debug,run
import sqlite3

@route('/')
def player():
    return template('index.tpl')

debug(True)
run(reloader=True)
like image 554
Zanmato Avatar asked Nov 24 '12 16:11

Zanmato


1 Answers

I haven't used bottle, but most web frameworks require you to put your css/js/images in a particular directory (that you set via configuration). Usually it's called "static" or something similar.

I bet if you tried to load those CSS files directly in your browser:

http://localhost:8080/demo.css 

you'd get a 404.

The way you have it currently set up is what you'd do for traditional PHP/CGI stuff - your web server is looking for files on disk and serving them. Frameworks don't (generally) work like that - you set up routing rules.

You did that with the @route('/') decorator - by setting that up, you told bottle "any requests to http:// localhost:8080/ should run the player function and return whatever it generates." Notice you haven't set up any rules for your css files.

The other possibility is you're not referring to the CSS files correctly in your HTML. If you don't get a 404 when you load the CSS files directly, post the HTML and we can take a look at that.

Edit: Found this in the bottle doc:

http://bottlepy.org/docs/dev/tutorial.html#routing-static-files

Static files such as images or CSS files are not served automatically. You have to add a route and a callback to control which files get served and where to find them:
from bottle import static_file
@route('/static/<filename>')
def server_static(filename):
  return static_file(filename, root='/path/to/your/static/files')
like image 98
Rachel Sanders Avatar answered Sep 25 '22 21:09

Rachel Sanders