我有一个我想以下面的方式构建的URL字符串:
http://something.com/mainsite/key1/key2/key3/keyn
如何在我的URL映射中生成类似这样的内容,其中n是变量号?
我如何获得这些钥匙?
谢谢
最佳答案 有两种方法可以做到这一点:
>只需使用path
route converter:
@app.route("/mainsite/<path:varargs>")
def api(varargs=None):
# for mainsite/key1/key2/key3/keyn
# `varargs` is a string contain the above
varargs = varargs.split("/")
# And now it is a list of strings
>注册您自己的custom route converter(有关详细信息,请参阅Werkzeug’s documentation):
from werkzeug.routing import BaseConverter, ValidationError
class PathVarArgsConverter(BaseConverter):
"""Convert the remaining path segments to a list"""
def __init__(self, url_map):
super(PathVarArgsConverter, self).__init__(url_map)
self.regex = "(?:.*)"
def to_python(self, value):
return value.split(u"/")
def to_url(self, value):
return u"/".join(value)
app.url_map.converters['varargs'] = PathVarArgsConverter
你可以这样使用:
@app.route("/mainsite/<varargs:args>")
def api(args):
# args here is the list of path segments