【问题标题】:Using flask/blueprint for some static pages对一些静态页面使用烧瓶/蓝图
【发布时间】:2011-08-14 00:08:45
【问题描述】:

所以我只是有点困惑如何用烧瓶构建页面而不必说明每个视图。

如何制作一个蓝图,以便在我要加载的页面上获取?

说这些是我的示例页面

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”导入

对烧瓶非常陌生,也不是 python 专家。真的只需要一些愚蠢的:)

【问题讨论】:

    标签: python flask


    【解决方案1】:

    如果您想查看Blueprint 用法的示例,可以查看this answer

    关于您的问题的“模板自动查找”部分:就像文档中解释的那样,蓝图允许指定一个文件夹来查找静态文件和/或模板,这样您就不必指定完整的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的模板。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2012-09-27
      • 1970-01-01
      相关资源
      最近更新 更多