我用几个应用程序(如博客、代码、帐户等)实现了简单的网站。由于文件太大,我决定将一个 python 文件拆分为应用程序。除了 Flask 的基本功能之外,我不使用蓝图或其他东西 - 我想让它尽可能简单。 不幸的是,flask 仍在寻找模板
/site
|-> main.py
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')
# Import all views
from errors.views import * # Errors hasn't its specific prefix
from blog.views import *
from account.views import *
from mysite.views import *
if __name__ == "__main__":
app.run(debug=True)
|-> templates
...................
|->blog
|-> template
|-> _layout.html
|-> index.html
|-> post.html
|-> __init__.py
from main import app
import blog.views
|-> views
from blog import app
from flask import render_template
@app.route("/blog/", defaults={'post_id': None})
@app.route("/blog/<int:post_id>")
def blog_view(post_id):
if post_id:
return "Someday beautiful post will be here with id=%s" % post_id
else:
return "Someday beautiful blog will be here"
@app.route("/blog/tags/")
def tags_view():
pass
..........................
假设您有 2 个蓝图博客和帐户。您可以按如下方式划分博客和帐户的个人应用程序(蓝图):
myproject/
__init__.py
templates/
base.html
404.html
blog/
template.html
index.html
post.html
account/
index.html
account1.html
blog/
__init__.py
views.py
account/
__init__.py
views.py
在您的 blog/views.py 中,您可以渲染如下模板:
@blog.route('/')
def blog_index():
return render_template('blog/index.html')
@account.route('/')
def account_index():
return render_template('account/index.html')
..等等
将
template_folder='templates'
添加到每个应用程序蓝图声明中:
account = Blueprint('account', __name__, template_folder='templates')
详情:https://flask.palletsprojects.com/en/2.0.x/blueprints/#templates
更多改进
app = Flask(__name__)
current_dir = os.getcwd() # To get the Template folder dynamicly
templates_bp = Blueprint('templates', __name__, template_folder=app.root_path)