简体   繁体   中英

Bottle web app not serving static css files

My bottle web application is not serving my main.css file despite the fact I am using the static_file method.

app.py

from bottle import *
from xml.dom import minidom
@route('/')
def index():
    return template("index")

@route('/glossaryXML')
def glossary():
    doc_def = minidom.parse("table_definitions.xml")
    terms = doc_def.getElementsByTagName("str_term")
    defins = doc_def.getElementsByTagName("str_definition")
    return template("list", terms=terms, defins=defins)

@route('<filename>.css')
def stylesheets(filename):
    return static_file(filename, root='static')

@error(404)
def fourofour(error):
    return "Error"

run(host='localhost', port=8080, debug=True)

The page I am trying to access is the index page, in which index.tpl looks like

<!DOCTYPE HTML>
<html>
    <head>
        <title>ICT Applications Glossary</title>
        <link type="text/css" href="main.css" rel="stylesheet">
    </head>
    <body>
        It works
    </body>
</html>

My CSS file is located in a folder named "static" which is in my root folder

Instead specify your static route like this

@route('/<filename:path>')
def send_static(filename):
    return static_file(filename, root='static/')

This will serve any file in your static directory though not just css.

To make it stylesheet specific

@get('/<filename:re:.*\.css>')
def stylesheets(filename):
    return static_file(filename, root='static/')

Note: for the latter option you could put stylesheets in their own directory 'static/css' or just 'css' and keep them separate from other static resources (scripts, images etc.) to do this just specify the root parameter to be that directory eg `root='static/css'.

There are 2 problems that I can see:

  • The route for the CSS files should begin with a slash, ie.

     @route('/<filename>.css') 
  • Only the matching part of the pattern is passed to stylesheets() in the filename argument, eg instead of main.css , it will be main . Change the code to this:

     @route('/<filename>.css') def stylesheets(filename): return static_file('{}.css'.format(filename), root='static') 

或者......将main.css文件重命名为main.tpl ,使用<style></style>重命名,将其与其他模板一起移动到/ views目录中,然后只需添加到返回行的开头:

return (template ("main"), template ("list", terms=terms, defins=defins))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM