如何获取bottle.py动态路由的URL?

时间:2014-10-20 05:32:32

标签: python bottle

我刚开始使用bottle.py。由于我的应用程序未部署为站点根目录。我使用get_url作为重定向代码,如下所示:

@myapp.route("/")
def index():
    redirect(myapp.get_url("/hello"), name=name)

例如,如果将应用程序部署到http // www.mysite.com / cgi-bin / myapp.py,它将成功重定向到http // www.mysite.com / cgi-bin / myapp.py /喂

现在的问题是如何重定向到动态路由?例如

@myapp.route("/hello/<name>")
def hello(name):
     .....
     return template(...)

@myaap.route("/")
def index():
   #How to redirect it to /hello/<name>?????

现在我想将页面重定向到路由“/ hello /”,但是get_url不接受它。它不适用于动态路线。

我不会写自己的“my_get_url”来处理它。我认为已经将瓶子应用程序部署到非根站点的每个人都应该已经面对并解决了这个问题......

任何评论都表示赞赏。

谢谢!

2 个答案:

答案 0 :(得分:1)

您应该同时使用名称和路线,并按名称引用路线。

例如:

@app.get(path="/admin/customers/single/messages/system_messages/delete/<message_id:int>",
         name="admin.customers.single.messages.system_messages.delete",
         _run_functions_before=[
             user_has_permissions([UserPermissionForCustomer.super_user_access])
         ]
         )
def delete_system_message(resources, message_id):
    """
    @param resources:
    @type resources: 
    @param message_id:
    @type message_id: int
    @return:
    """
    system_messages_logic = SystemMessagesLogic(resources)
    system_messages_logic.delete_system_message(message_id)
    return list_system_messages(resources)

在上面的示例中,您可以参考以下路线:

 redirect(app.get_url("admin.customers.single.messages.system_messages.delete", message_id=message_id))

答案 1 :(得分:0)

由于您已将路线指定为

@myapp.route("/hello/<name>")

重定向不起作用

redirect(myapp.get_url("/hello"), name=name)

而是应将整个网址指定为/hello/somename/

也就是说,如果尝试传递变量name的值,就像在代码中一样,它可以写成

@myapp.route("/hello/<name>")
def hello(name):
     .....
     return template(...)

@myaap.route("/")
def index():
    redirect(myapp.get_url("/hello/") + '/' + name)