简体   繁体   中英

Difference between Pluggable Views and Blueprint in Python Flask

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

I don't know comparing them is correct or not but,

According to 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.

In the example, it defines a get_template_name method in the view and re-uses it in other view. That's what pluggable views are for.

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 Blueprints are just an easier way for organizing larger projects. They don't give you the feature Pluggable Views offer.

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)

Then you register these blueprints to your application object.

As far as routing goes, Pluggable Views (aka class-based views) is far more superior than Blueprints, which are just a bunch of functions with routes decorators.

In Pluggable Views paradigm, it facilitates code reuse code by organizing view logics in classes and subclass them. URL routes are registered with app.add_url_rule() call, this is great because it follows the S in SOLID principles (separate of concerns). In Blueprints approach, each front end view logic are encapsulated within the view functions, which aren't suited well for code reuse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM