【发布时间】:2018-12-10 14:49:32
【问题描述】:
注意:对最初的问题进行了大量编辑,包括最小示例。原始标题也具有误导性。
我花了几天时间将一堆单独的应用程序和帮助模块重构为一个带有蓝图的大包。实际的 Flask 内容在包的顶级目录下几级,我已经在该目录中完成了所有测试。
打包并安装包后,url_for() 调用不再起作用,因为应用程序规则中的端点现在包括蓝图视图函数的完整路径,而不仅仅是最后一点。
这是一个说明问题的最小示例(文件附加在下面):
当应用程序在其自己的目录中运行时,规则如下所示:
$ python foo/test.py
[<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/bar/' (HEAD, OPTIONS, GET) -> bar.index>,
<Rule '/' (HEAD, OPTIONS, GET) -> index>,
<Rule '/other' (HEAD, OPTIONS, GET) -> other>]
...这是从模块的基本目录运行时的样子:
$ python test.py
[<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/bar/' (HEAD, OPTIONS, GET) -> foo.bar.index>,
<Rule '/' (HEAD, OPTIONS, GET) -> index>,
<Rule '/other' (HEAD, OPTIONS, GET) -> other>]
注意“/”和“/other”(在应用程序中定义)的端点是如何保持不变的,而“/bar/”(在蓝图中定义)的端点将包名称“foo”放在前面。目前我所有的 url_for() 调用都使用“短”端点路径,我想保持这种方式,部分我讨厌必须添加完整的包名几十次,也因为我不确定目录树将永远保持不变。
这是文件的样子:
$ tree
.
├── foo
│ ├── app.py
│ ├── bar.py
│ ├── __init__.py
│ └── test.py
└── test.py
$ cat ./foo/app.py
import flask
from bar import blp
app = flask.Flask(__name__)
app.register_blueprint(blp, url_prefix='/bar')
@app.route('/')
def index():
pass
@app.route('/other')
def other():
pass
$ cat ./foo/bar.py
import flask
blp = flask.Blueprint(__name__, __name__)
@blp.route('/')
def index():
pass
$ cat ./foo/__init__.py
$ cat ./foo/test.py
from app import app
import pprint
rules = app.url_map.__dict__['_rules']
pprint.pprint(rules)
$ cat ./test.py
from foo.app import app
import pprint
rules = app.url_map.__dict__['_rules']
pprint.pprint(rules)
【问题讨论】:
-
你读过this question吗?
-
我做了(在问我的问题之前),但那是关于为 URL 添加前缀,而不是应用程序端点(= Python 函数)
-
你能把WSGI脚本移到flask_application文件夹吗?
-
注意,我已将问题修改为一个最小的、独立的示例来说明问题。