Register this extension with the flask app.

        :param app: A flask application
553719
def init_app(self, app):
        
        # Save this so we can use it later in the extension
        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}
        app.extensions['flask-graphql-auth'] = self

        self._set_default__configuration_options(app)
405650
def register_views(self, app):
        

        # Wrap the views in an arbitrary number of decorators.
        def wrap_view(view):
            if self.decorators:
                for decorator in self.decorators:
                    view = decorator(view)
            return view

        if self.config.get('swagger_ui', True):
            uiversion = self.config.get('uiversion', 3)
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__,
                url_prefix=self.config.get('url_prefix', None),
                subdomain=self.config.get('subdomain', None),
                template_folder=self.config.get(
                    'template_folder', 'ui{0}/templates'.format(uiversion)
                ),
                static_folder=self.config.get(
                    'static_folder', 'ui{0}/static'.format(uiversion)
                ),
                static_url_path=self.config.get('static_url_path', None)
            )

            blueprint.add_url_rule(
                self.config.get('specs_route', '/apidocs/'),
                'apidocs',
                view_func=wrap_view(APIDocsView().as_view(
                    'apidocs',
                    view_args=dict(config=self.config)
                ))
            )

            # backwards compatibility with old url style
            blueprint.add_url_rule(
                '/apidocs/index.html',
                view_func=lambda: redirect(url_for('flasgger.apidocs'))
            )
        else:
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__
            )

        for spec in self.config['specs']:
            self.endpoints.append(spec['endpoint'])
            blueprint.add_url_rule(
                spec['route'],
                spec['endpoint'],
                view_func=wrap_view(APISpecsView.as_view(
                    spec['endpoint'],
                    loader=partial(
                        self.get_apispecs, endpoint=spec['endpoint'])
                ))
            )

        app.register_blueprint(blueprint)
821928
def proxy(self) -> bool:
        
        if self.app is None:
            return False
        return bool(cast(Any, self.app).proxy)
510751
def init_app(self, app, **kwargs):
        
        self.init_config(app)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        # Register blueprint in order to register template and static folder.
        app.register_blueprint(Blueprint(
            'invenio_theme',
            __name__,
            template_folder='templates',
            static_folder='static',
        ))

        # Register frontpage blueprint if enabled.
        if app.config['THEME_FRONTPAGE']:
            app.register_blueprint(blueprint)

        # Initialize breadcrumbs.
        item = self.menu.submenu('breadcrumbs')
        item.register(app.config['THEME_BREADCRUMB_ROOT_ENDPOINT'], _('Home'))

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        # Save reference to self on object
        app.extensions['invenio-theme'] = self
806919
def init_app(self, app):
        """"""
        # Set default Flask config option.
        app.config.setdefault('STATICS_MINIFY', False)

        # Select resources.
        self.all_resources = ALL_RESOURCES_MINIFIED if app.config.get('STATICS_MINIFY') else ALL_RESOURCES
        self.all_variables = ALL_VARIABLES

        # Add this instance to app.extensions.
        if not hasattr(app, 'extensions'):
            app.extensions = dict()
        if 'statics' in app.extensions:
            raise ValueError('Already registered extension STATICS.')
        app.extensions['statics'] = _StaticsState(self, app)

        # Initialize blueprint.
        name = 'flask_statics_helper'
        static_url_path = '{0}/{1}'.format(app.static_url_path, name)
        self.blueprint = Blueprint(name, __name__, template_folder='templates', static_folder='static',
                                   static_url_path=static_url_path)
        self.blueprint.add_app_template_global(self.all_variables, '_flask_statics_helper_all_variables')
        self.blueprint.add_app_template_global(self.all_resources, '_flask_statics_helper_all_resources')
        app.register_blueprint(self.blueprint)
1370870
def register_model(self, app, model_name, field_type, field_definitions):
        
        from django.apps import apps
        import collections

        app_label = app

        if isinstance(field_definitions, str):
            field_definitions = [field_definitions]
        elif not isinstance(field_definitions, collections.Iterable):
            raise ImproperlyConfigured(_('Field configuration for %(app)s should be a string or iterable') % {'app': app})

        if field_type not in ('ForeignKey', 'ManyToManyField'):
            raise ImproperlyConfigured(_('`field_type` must be either `"ForeignKey"` or `"ManyToManyField"`.'))

        try:
            if not hasattr(model_name, "_meta"):
                app_config = apps.get_app_config(app)
                app_label = app_config.label
                model = app_config.get_model(model_name)
            else:
                model = model_name
                model_name = model._meta.model_name
            opts = model._meta
            if app_label not in self._model_registry:
                self._model_registry[app_label] = []
            if model not in self._model_registry[app_label]:
                self._model_registry[app_label].append(model)
        except LookupError:
            raise ImproperlyConfigured('Model "%(model)s" doesn\'t exist in app "%(app)s".' % {'model': model_name, 'app': app})

        if not isinstance(field_definitions, (tuple, list)):
            field_definitions = [field_definitions]

        for fld in field_definitions:
            extra_params = {'to': 'categories.Category', 'blank': True}
            if field_type != 'ManyToManyField':
                extra_params['on_delete'] = CASCADE
                extra_params['null'] = True
            if isinstance(fld, str):
                field_name = fld
            elif isinstance(fld, dict):
                if 'name' in fld:
                    field_name = fld.pop('name')
                else:
                    continue
                extra_params.update(fld)
            else:
                raise ImproperlyConfigured(
                    _("%(settings)s doesn't recognize the value of %(app)s.%(model)s") % {
                        'settings': 'CATEGORY_SETTINGS',
                        'app': app,
                        'model': model_name})
            registry_name = ".".join([app_label, model_name.lower(), field_name])
            if registry_name in self._field_registry:
                continue

            try:
                opts.get_field(field_name)
            except FieldDoesNotExist:
                self._field_registry[registry_name] = FIELD_TYPES[field_type](**extra_params)
                self._field_registry[registry_name].contribute_to_class(model, field_name)
372898
def init_app(self, app):
        

        self.__app = app
        self.__app.before_first_request(self.__setup)

        self.tracer.enabled = self.__app.config.get('TRACE_ENABLED', self.tracer.enabled)
463094
def bind_extensions(app):
    
    # bind plugin to app object
    app.db = app.config['PUZZLE_BACKEND']
    app.db.init_app(app)

    # bind bootstrap blueprints
    bootstrap.init_app(app)
    markdown(app)

    @app.template_filter('islist')
    def islist(object):
        return isinstance(object, (tuple, list))
963331
def init_app(self, app):
        
        app.config.setdefault('EDITS_URL', '/edits')
        app.config.setdefault('EDITS_PREVIEW', True)
        app.config.setdefault('EDITS_SUMMERNOTE', False)

        if 'EDITS_PATH' not in app.config:
            raise Exception('EDITS_PATH not set in app configuration.')

        if os.path.isfile(app.config['EDITS_PATH']):
            with open(app.config['EDITS_PATH']) as f:
                _db = json.loads(f.read(), object_pairs_hook=OrderedDict)
        else:
            _db = OrderedDict()

        app.jinja_env.add_extension('flask.ext.edits.EditableExtension')
        app.jinja_env.edits = _db
        app.jinja_env.edits_preview = app.config['EDITS_PREVIEW']
        app.jinja_env.edits_cache = copy_cache(app.jinja_env.cache)

        if app.config['EDITS_PREVIEW']:
            app.jinja_env.cache = None

        app.register_blueprint(edits, url_prefix=app.config['EDITS_URL'])
567638
def init_app(self, app):
        
        self.app = app
        self.__blueprint__ = Blueprint(
            self.__name__,
            self.__name__,
            url_prefix=self.__prefix__,
        )

        for url, name, methods in self.__urls__:
            self.blueprint.add_url_rule(
                url,
                view_func=getattr(self, name),
                endpoint=name.replace("r_", ""),
                methods=methods
            )
        self.app = self.app.register_blueprint(self.blueprint)

        return self.blueprint
1341325
def init_app(application):
    
    for code in werkzeug.exceptions.default_exceptions:
        application.register_error_handler(code, handle_http_exception)
429911
def with_app(f):
    """"""
    @wraps(f)
    def decorator(*args, **kwargs):
        app = create_app()
        configure_extensions(app)
        configure_views(app)
        return f(app=app, *args, **kwargs)
    return decorator
525499
def app_state(self):
        
        try:
            return current_app.extensions[self.name]
        except KeyError:
            raise ServiceNotRegistered(self.name)
911687
def init_app(self, app):
        
        self.init_config(app)

        self.wrap_errorhandler(app)
        app.extensions['invenio-pages'] = _InvenioPagesState(app)

        return app.extensions['invenio-pages']
381576
def init_app(self, app):
        """"""
        app.add_url_rule(self.request_token_url, view_func=self.request_token,
                         methods=[u'POST'])
        app.add_url_rule(self.access_token_url, view_func=self.access_token,
                         methods=[u'POST'])
        app.add_url_rule(self.register_url, view_func=self.register,
                         methods=[u'GET', u'POST'])
        app.add_url_rule(self.authorize_url, view_func=self.authorize,
                         methods=[u'GET', u'POST'])
1275848
def create_app():
    

    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Initialize Flask extensions
    db = None
    mail = Mail(app)  # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask_user UserMixin !!!
    class UsernameIndex(GlobalSecondaryIndex):
        class Meta:
            read_capacity_units = 1
            write_capacity_units = 1
            projection = AllProjection()

        username = UnicodeAttribute(hash_key=True)

    class EmailIndex(GlobalSecondaryIndex):
        class Meta:
            read_capacity_units = 1
            write_capacity_units = 1
            projection = AllProjection()

        email = UnicodeAttribute(hash_key=True)

    class User(Model, UserMixin):
        class Meta:
            table_name = 'users'

        id = UnicodeAttribute(hash_key=True, default=lambda: str(uuid.uuid1()))
        active = BooleanAttribute()

        # User authentication information
        username = UnicodeAttribute(null=True)
        password = UnicodeAttribute(null=True)

        username_index = UsernameIndex()

        # User email information
        email = UnicodeAttribute(null=True)
        email_confirmed_at = UTCDateTimeAttribute(null=True)

        email_index = EmailIndex()

        # User information
        first_name = UnicodeAttribute(null=True)
        last_name = UnicodeAttribute(null=True)


    # Setup Flask-User
    user_manager = UserManager(app, db, User)

    # Create all database tables
    print('create_schema()')
    user_manager.db_manager.create_all_tables()
    print('created_schema()')

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% block content %}
                <h2>Home page</h2>
                <p>This page can be accessed by anyone.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required  # Use of @login_required decorator
    def members_page():
        return render_template_string("""
            {% block content %}
                <h2>Members page</h2>
                <p>This page can only be accessed by authenticated users.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    return app
847461
def _init_app(self, app):
        
        app.handle_exception = partial(self.error_router, app.handle_exception)
        app.handle_user_exception = partial(self.error_router, app.handle_user_exception)

        if len(self.resources) > 0:
            for resource, urls, kwargs in self.resources:
                self._register_view(app, resource, *urls, **kwargs)