使用Flask/蓝图处理一些静态页面

4 投票
1 回答
4067 浏览
提问于 2025-04-16 23:33

我对如何用Flask构建页面有点困惑,不想每次都要明确写出每个视图。

我该如何创建一个蓝图,让它自动识别我想加载的页面呢?

比如说,这些是我的示例页面:

templates/
   layout.html
   section1/
     subsection/index.html
     subsection2/index.html
   section2
     subsection/index.html
       childofsubsection/index.html

我希望当我访问example.com/section1/subsection/时,它能自动找到对应的页面,而不需要我特别去指定。文档http://flask.pocoo.org/docs/blueprints/对这个问题的解释很接近,但我还是有点迷糊。

from flask import Flask
from yourapplication.simple_page import simple_page

app = Flask(__name__)
app.register_blueprint(simple_page)

另外,我也不太确定这个内容应该放在哪里?看起来应该放在application.py里,但又说要从“yourapplication”导入。

我对Flask非常陌生,也不是Python专家。真的需要一些简单易懂的解释 :)

1 个回答

13

如果你想看看如何使用 Blueprint,可以参考这个回答

关于你提到的“模板自动查找”部分:就像文档里说的,蓝图(blueprints)可以让你指定一个文件夹,里面放着静态文件和/或模板。这样的话,在调用 render_template() 时,你就不需要写出模板文件的完整路径,只需要写文件名就可以了。

如果你想让你的视图“自动”知道该选择哪个文件,你需要做一些小技巧。比如,可以在你的视图上加一个装饰器,这样它就能根据函数名来选择模板文件。这个装饰器大概是这样的:

from functools import wraps
from flask import render_template

def autorender(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        context = func(*args, **kwargs)
        return render_template('%s.html' % func.func_name, **context)
    return wrapper

然后你只需要在视图中返回一个字典作为上下文(如果没有上下文,可以返回一个空字典):

@my_blueprint.route('/')
@autorender
def index():
    return {'name': 'John'} # or whatever your context is

这样它就会自动选择名为 index.html 的模板。

撰写回答