Skip to content

Instantly share code, notes, and snippets.

@playpauseandstop
Created October 17, 2012 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save playpauseandstop/3904673 to your computer and use it in GitHub Desktop.
Save playpauseandstop/3904673 to your computer and use it in GitHub Desktop.
Improve registering blueprints in Flask application
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