栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Flask中寻找url_for的逆函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Flask中寻找url_for的逆函数

我使用以下

route_from
功能:

from flask.globals import _app_ctx_stack, _request_ctx_stackfrom werkzeug.urls import url_parsedef route_from(url, method = None):    appctx = _app_ctx_stack.top    reqctx = _request_ctx_stack.top    if appctx is None:        raise RuntimeError('Attempted to match a URL without the '     'application context being pushed. This has to be '     'executed when application context is available.')    if reqctx is not None:        url_adapter = reqctx.url_adapter    else:        url_adapter = appctx.url_adapter        if url_adapter is None: raise RuntimeError('Application was not able to create a URL '         'adapter for request independent URL matching. '         'You might be able to fix this by setting '         'the SERVER_NAME config variable.')    parsed_url = url_parse(url)    if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name:        raise NotFound()    return url_adapter.match(parsed_url.path, method)

我通过查看

url_for
并将其反转的实现来编写此代码。

url
参数可以是一个完整的URL或只是路径信息部分。返回值是带有端点名称的元组和
dict
带有参数的a。

免责声明:我尚未对其进行广泛的测试。我原本打算最终将它作为请求请求提交,但似乎从来没有经过全面测试并编写了一些单元测试。如果它不适合您,请告诉我!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号