我通过在帮助程序蓝图 python 文件中创建一个类以稍微不同的方式解决了这个问题。这样我就可以调用一次来加载类,然后将结果传递给主 python 脚本中的蓝图函数。当我加载类时,我可以传递我配置的任何属性。我喜欢这种方法,因为它使我的代码更干净。
如果你想下载我在这里输入的代码,也可以在https://github.com/dacoburn/example-flask-blueprints找到。我在 github 上添加了关于 python 文件中发生了什么的更多细节的评论。
我的文件夹结构是: src |___main.py |___routes |___index.py |___example.py |___templates |___index.html |___example.html
main.py
from flask import Flask
import os
from routes.index import Index
from routes.example import Example
app = Flask(__name__)
index = Index("Example User")
example = Example("Random Arg")
app.register_blueprint(index.index)
app.register_blueprint(example.example)
if __name__ == '__main__':
port = int(os.environ.get('APP_PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
index.py
from flask import render_template, Blueprint
class Index:
def __init__(self, username):
self.username = username
self.index = self.create_index()
def create_index(self):
index_page = Blueprint("index", __name__)
@index_page.route("/", methods=['GET'])
def index():
return render_template("index.html", username=self.username)
return index_page
example.py
from flask import render_template, Blueprint
class Example:
def __init__(self, arg):
self.arg = arg
self.example = self.create_example()
def create_example(self):
example_page = Blueprint("example", __name__)
@example_page.route("/<username>", methods=['GET'])
def example(username):
return render_template("example.html",
username=username,
arg=self.arg)
return example_page
index.html
<html>
<head>
<title>Example Page</title>
</head>
<body>
<p>Hello {{ username }}</p>
<br>
This page also has a redirect to another route:
<ul>
<li><a href="/{{ username }}">Example Page</a></li>
</ul>
</body>
</html>
example.html
<html>
<head>
<title>Example Page 2</title>
</head>
<body>
<p>Hello {{ username }}</p>
<br>
Here is the random argument: {{ arg }}
<br>
<br>
This page also has a link to the main page:
<ul>
<li><a href="{{ url_for('index.index') }}">Index Page</a></li>
</ul>
</body>
</html>