librelist archives

« back to archive

Blueprints

Blueprints

From:
Sergey Koval
Date:
2011-07-30 @ 17:49
Hello,

 I have some questions regarding blueprints and design considerations
behind them.

 Lets take following example: I want to have a blueprint that can
generate administrative interface for one SQLAlchemy model (contains
some views - list view, new/edit form, etc). Naive way to implement
this would be to have multiple blueprints, however because blueprints
are instances of Blueprint class, it is not directly possible. So, I
will have to implement blueprint factory, which will accept model as
input parameter and return blueprint instance which will manage this
particular model.

 However, if blueprints were working on a class level, it can look like:

class ModelAdmin(Blueprint):
    def __init__(self, model):
        super(ModelAdmin, self).__init__(model.__name__, 'model.admin')

        self.model = model

    @route('/')
    def index(self):
        pass

    @route('/edit/<pk>/')
    def edit(pk):
        pass

Using this class, I can add as many blueprints as possible that do
same, but for different models:

app.register_blueprint(ModelAdmin(User), url_prefix='user')
app.register_blueprint(ModelAdmin(Car), url_prefix='car')

which makes it really extensible and keeps code clean.

 There's nice example in flask-admin, which dynamically creates
blueprint instance, stores passed models to the instance, then creates
views and associates them with the blueprint, all in one function:
https://github.com/wilsaj/flask-admin/blob/master/flaskext/admin/__init__.py#L82

 So, list of questions:
1. Is factory expected and desired pattern in the Flask, when working
with blueprints?
2. Is there better way to do it?

Thank you,
Serge.