简体   繁体   English

如何在提供静态文件时将@ bottle.route转换为bottle.route()?

[英]How to convert @bottle.route to bottle.route() when serving static files?

I usually use the method version to handle routing in bottle 我通常使用方法版本来处理瓶中的路由

bottle.route("/charge", "GET", self.charge)

The bottle docs heavily rely on the @route decorator to handle the routing and I have one case I do not know how to convert into my favorite version. 瓶子文档严重依赖@route装饰器来处理路由,我有一个案例,我不知道如何转换成我最喜欢的版本。 The docs on serving static files use the example 提供静态文件的文档使用该示例

from bottle import static_file

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

Is there a way to turn that into some kind of 有没有办法把它变成某种形式

bottle.route("/static", "GET", static_file)

construction? 施工? In particular I am confused by how to pass the filename and root parameters to static_file . 特别是我对如何将filenameroot参数传递给static_file感到困惑。

The accepted answer doesn't solve your problem nicely, so I'll chime in. You seem to be trying to use Bottle's static_file as a route target, but it's not meant to be used that way. 接受的答案并没有很好地解决你的问题,所以我会static_file 。你似乎试图使用Bottle的static_file作为路由目标,但它并不意味着以这种方式使用。 As the example you cited demonstrates, static_file is meant to be called from within a route target function. 正如你所列举的例子表明, static_file意味着从一个路由目标函数调用。 Here's a complete working example: 这是一个完整的工作示例:

import bottle

class AAA(object):
    def __init__(self, static_file_root):
        self.static_file_root = static_file_root

    def assign_routes(self):
        bottle.route('/aaa', 'GET', self.aaa)
        bottle.route('/static/<filename:path>', 'GET', self.send_static)

    def aaa(self):
        return ['this is aaa\n']

    def send_static(self, filename):
        return bottle.static_file(filename, self.static_file_root)

aaa = AAA('/tmp')
aaa.assign_routes()
bottle.run(host='0.0.0.0', port=8080)

Example usage: 用法示例:

% echo "this is foo" > /tmp/foo
% curl http://localhost:8080/static/foo
this is foo

Hope this helps. 希望这可以帮助。

since you want to use single method, you must pass the parameters to the static_file by yourself, and use re to parse them at first. 因为你想使用单个方法,你必须自己将参数传递给static_file ,并使用re来解析它们。

the code will looks like this: 代码将如下所示:

from bottle import Router

app.route('/static/:filename#.*#', "GET", static_file(list(Router()._itertokens('/static/:filename#.*#'))[1][2], root='./static/'))

this is a little long and if you want to parse the parameter outside, than you may add another parse function. 这有点长,如果你想在外面解析参数,那么你可以添加另一个解析函数。

I know you want to make all your routers looks clean and in good order, but the decorator is to rich the function but keep the function itself clean, for AOP, so why not try to use decorators in this situation. 我知道你想让你的所有路由器看起来干净整洁,但装饰器要丰富功能但保持功能本身干净,对于AOP,所以为什么不尝试在这种情况下使用装饰器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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