简体   繁体   中英

Including subdirectories in static routing for Bottle.py web framework

I'm trying to use a bootstrap themed site with a lot of vendor plugins, and use bottle.py for a web server with a few API services built in.

I was wondering, if for static routing, is there anyway to call all the subdirectories in the routing request? I want to do something like this (instead of creating a seperate routing path for each subdir)

 @route('/vendors/*/<filename>')
 def vendors__static(filename):
     return static_file(filename, root='./vendors/*/')

Is this at all possible? Is there a lookup time cost involved? Thanks!

Yes, Bottle does support globbing the URI path; see the :path filter . Here's a complete example based on your original code:

from bottle import Bottle, route, static_file, response

app = Bottle()

@app.route('/vendors/<vendor_path:path>/<filename>')
def vendors__static(vendor_path, filename):
    vendors = vendor_path.split('/')
    responses = []
    for vendor in vendors:
        # you read the file here and insert its contents
        responses.append('<contents of ./vendors/{}/{} go here>'.format(vendor, filename))
    response.content_type = 'text/plain'
    return '\n'.join(responses)

app.run(host='127.0.0.1', port=8080)

Then, a call to http://127.0.0.1:8080/vendors/v1/v2/v3/myfile produces:

<contents of ./vendors/v1/myfile go here>
<contents of ./vendors/v2/myfile go here>
<contents of ./vendors/v3/myfile go here>

As an aside: static_file returns to the client the contents of one file. You'll need to think about how you intend to "return" multiple files to the client. Perhaps you can concatenate their contents (as in my example above)? In any case, this is a separate question from the Bottle routing so I'll leave it at that.

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