gpt4 book ai didi

python - Python Flask 中可插入 View 和蓝图的区别

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:05 24 4
gpt4 key购买 nike

Python Flask 中的 PluggableViews 和 Blueprint 有什么区别?

最佳答案

我不知道比较它们是否正确但是,

根据 Flask Documentation :

Flask 0.7 introduces pluggable views inspired by the generic views from Django which are based on classes instead of functions. The main intention is that you can replace parts of the implementations and this way have customizable pluggable views.

在示例中,它在 View 中定义了一个get_template_name 方法并在其他 View 中重新使用它。这就是可插入 View 的用途。

from flask.views import View

class ListView(View):

def get_template_name(self):
raise NotImplementedError()

def render_template(self, context):
return render_template(self.get_template_name(), **context)

def dispatch_request(self):
context = {'objects': self.get_objects()}
return self.render_template(context)

class UserView(ListView):

def get_template_name(self):
return 'users.html'

def get_objects(self):
return User.query.all()

Flask 蓝图只是组织大型项目的一种更简单的方法。他们没有为您提供可插入 View 提供的功能。

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

simple_page = Blueprint('simple_page', __name__,
template_folder='templates')

@simple_page.route('/', defaults={'page': 'index'})
@simple_page.route('/<page>')
def show(page):
try:
return render_template('pages/%s.html' % page)
except TemplateNotFound:
abort(404)

然后您将这些蓝图注册到您的应用程序对象。

关于python - Python Flask 中可插入 View 和蓝图的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40943923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com