Created
October 17, 2012 09:31
-
-
Save playpauseandstop/3904673 to your computer and use it in GitHub Desktop.
Improve registering blueprints in Flask application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask.ext.sqlalchemy import SQLAlchemy | |
class App(Flask): | |
""" | |
Custom ``Flask`` class. | |
""" | |
def register_blueprint(self, mixed, **kwargs): | |
""" | |
Register blueprint to application and store all initialized extensions | |
as ``blueprint.extensions`` attribute. | |
""" | |
if isinstance(mixed, basestring): | |
blueprint_name = '{}_blueprint'.format(mixed) | |
module_name = 'appname.{}'.format(mixed) | |
blueprint = import_string(module_name + ':' + blueprint_name) | |
else: | |
blueprint = mixed | |
super(App, self).register_blueprint(blueprint, **kwargs) | |
if not hasattr(blueprint, 'extensions'): | |
setattr(blueprint, 'extensions', self.extensions) | |
# Initialize Flask application | |
app = App('appname') | |
app.config['SQLALCHEMY_SCHEMA_URI'] = 'sqlite:////tmp/appname.db' | |
# Initialize SQLAlchemy extension | |
db = SQLAlchemy(app) | |
# Register blueprint from ``appname.bluename`` | |
app.register_blueprint('bluename') | |
# Register blueprint from ``appname.another_bluename`` and custom settings | |
app.register_blueprint('another_bluename', url_prefix='/another') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment