1 回答
TA贡献1859条经验 获得超6个赞
我检查了add_route的源代码
它添加route
到两个对象:self.routes
and self.router
( app.routes
and app.router
) 这会产生问题。
def add_route(self, route): """ Add a route object, but do not change the :data:`Route.app` attribute.""" self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare()
self.router
是具有rules
, builder
, static
dyna_routes
, _dyna_regexes
如果您在添加新路线之前和之后检查它们,那么您会看到builder
和中的变化static
。
def addRoute():
print('--- before ---')
print(app.router.rules)
print(app.router.builder)
print(app.router.static)
print(app.router.dyna_routes)
app.route('/route/hello')(lambda :'Hello World')
print('--- after ---')
print(app.router.rules)
print(app.router.builder)
print(app.router.static)
print(app.router.dyna_routes)
print('Routes after calling /add:\n' + '\n'.join([str(route) for route in app.routes]))
redirect('route/hello')
如果我'/route/hello'从中删除builder然后停止工作但仍然显示它们,那么你将不得不从两者中删除static-但它们没有为此的特殊功能:)'/route/hello'app.routes'/route/hello'app.routesapp.router
def removeRoute():
prefix = '/route/hello'
del app.router.builder[prefix]
del app.router.static['GET'][prefix]
print('Routes after calling /remove:\n' + '\n'.join([str(route) for route in app.routes]))
redirect('/route/hello')
我的完整代码:
import bottle
from bottle import redirect, abort
def addRoute():
print('--- before /add ---')
print(app.router.rules)
print(app.router.builder)
print(app.router.static)
print(app.router.dyna_routes)
print(app.router.dyna_regexes)
print('Routes before calling /add:\n' + '\n'.join([str(route) for route in app.routes]))
app.route('/route/hello')(lambda :'Hello World')
print('--- after /add ---')
print(app.router.rules)
print(app.router.builder)
print(app.router.static)
print(app.router.dyna_routes)
print(app.router.dyna_regexes)
print('Routes after calling /add:\n' + '\n'.join([str(route) for route in app.routes]))
redirect('route/hello')
def removeRoute():
prefix = '/route/hello'
print('--- before /remove ---')
print(app.router.rules)
print(app.router.builder)
print(app.router.static)
print(app.router.dyna_routes)
print(app.router.dyna_regexes)
print('Routes before calling /remove:\n' + '\n'.join([str(route) for route in app.routes]))
del app.router.builder[prefix]
del app.router.static['GET'][prefix]
print('--- after /remove ---')
print(app.router.rules)
print(app.router.builder)
print(app.router.static)
print(app.router.dyna_routes)
print(app.router.dyna_regexes)
print('Routes before calling /remove:\n' + '\n'.join([str(route) for route in app.routes]))
redirect('/route/hello')
if __name__ == '__main__':
app = bottle.app()
app.route('/add')(addRoute)
app.route('/remove')(removeRoute)
print('Initial routes:\n' + '\n'.join([str(route) for route in app.routes]))
bottle.run(app, host = 'localhost', port = 8080)
添加回答
举报