【问题标题】:How to get the URL of a bottle.py dynamic route?如何获取bottle.py 动态路由的URL?
【发布时间】:2017-11-01 20:52:09
【问题描述】:

我刚开始使用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”来处理它。我认为每个将瓶子应用程序部署到非根站点的人都应该已经面临并解决了这个问题......

欢迎评论。

谢谢!

【问题讨论】:

  • redirect(myapp.get_url("/hello%s" % name)??

标签: python bottle


【解决方案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))

【讨论】:

    【解决方案2】:

    既然你已经给出了路线

    @myapp.route("/hello/&lt;name&gt;")

    重定向不起作用

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

    而是应该将整个 url 指定为/hello/somename/

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

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

    【讨论】:

    • redirect(myapp.get_url("/hello/%s" % name) 不起作用。它会引发错误:“No route with that name”。get_url 的第一个参数看起来像必须是“路线名称”。
    • 试试redirect(myapp.get_url("/hello/")+name)之类的东西,看看编辑后的答案
    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2021-01-27
    • 2019-12-11
    • 2011-02-22
    • 2012-09-11
    相关资源
    最近更新 更多