Exemple #1
0
def init_extensions(app):
    db.init_app(app)
    db.app = app
    db.metadata.naming_convention = {
        "ix": 'ix_%(column_0_label)s',
        "uq": "uq_%(table_name)s_%(column_0_name)s",
        "ck": "ck_%(table_name)s_%(column_0_name)s",
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
        "pk": "pk_%(table_name)s"
    }
    # set constraint naming convention to sensible default, per
    # http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#configuring-constraint-naming-conventions

    assets.init_app(app)
    assets.app = app
    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    rq.init_app(app)
    app.rq = rq
    store.init_app(app)
    rest.init_app(app, flask_sqlalchemy_db=db,
                  preprocessors=restless_preprocessors)
    rest.app = app

    limiter.init_app(app)
    for handler in app.logger.handlers:
        limiter.logger.addHandler(handler)

    if app.config.get('DEBUG'):
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
        app.debug = True
Exemple #2
0
def register_extensions(app):
    """
    扩展实例化
    :param app:
    :return:
    """
    db.init_app(app)
    moment.init_app(app)
    migrate.init_app(app=app, db=db)
    cache.init_app(app)

    login_manager.init_app(app)
    # 登录过滤保护
    login_manager.exempt_views((user_bp, demo_bp, audio_bp, img_api_bp, ocr_api_bp))

    session.init_app(app)

    csrf.init_app(app)
    # csrf过滤保护
    csrf.exempt_views((demo_bp, audio_bp, img_api_bp, ocr_api_bp))

    # 定时任务 解决FLASK DEBUG模式定时任务执行两次
    if os.environ.get('FLASK_DEBUG', '0') == '0':
        scheduler.init_app(app)
        scheduler.start()
    elif os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        scheduler.init_app(app)
        scheduler.start()
Exemple #3
0
def configure_app(app, config=None):
    """Different ways of configurations."""

    # http://flask.pocoo.org/docs/api/#configuration
    app.config.from_object(DefaultConfig)

    # http://flask.pocoo.org/docs/config/#instance-folders
    app.config.from_pyfile('prod.py', silent=True)

    if config:
        app.config.from_object(config)

    # Use instance folder instead of env variables to make deployment easier.
    #app.config.from_envvar('%s_APP_CONFIG' % DefaultConfig.PROJECT.upper(), silent=True)

    #Redis Cache
    cache_config = {
        'CACHE_TYPE': DefaultConfig.CACHE_TYPE,
        'CACHE_REDIS_HOST': DefaultConfig.CACHE_REDIS_HOST,
        'CACHE_REDIS_PORT': DefaultConfig.CACHE_REDIS_PORT,
        'CACHE_REDIS_DB': DefaultConfig.CACHE_REDIS_DB,
        'CACHE_REDIS_PASSWORD': DefaultConfig.CACHE_REDIS_PASSWORD
    }

    cache.init_app(app, config=cache_config)
    RedisSession(app)
    socketio = SocketIO(app,
                        async_mode='eventlet',
                        message_queue=app.config['SOCKETIO_REDIS_URL'])
    socketio.on_namespace(Socket_conn('/deyunio'))
Exemple #4
0
def configure_extensions(app):
    db.app = app
    db.init_app(app)
    mail.init_app(app)
    cache.init_app(app)
    celery.conf.update(app.config)
    rd.init_app(app)
Exemple #5
0
def create_app():
	app = Flask(__name__)
	app.config['DEBUG'] = True

	app.config['USAGE_MONGODB_SETTINGS'] = {
		'db': 'flask',
		'host': 'mongodb://*****:*****@app.route('/cached')
	@cache.cached()
	def home_page():
		return {'msg': '/cached'}

	@app.route('/')
	def cache_page():
		return {'msg': '/'}

	return app
Exemple #6
0
def register_extensions(app):
    db.init_app(app)
    migrate = Migrate(app, db)
    jwt.init_app(app)
    mail.init_app(app)
    cache.init_app(app)
    limiter.init_app(app)
Exemple #7
0
def register_extensions(app):
    db.init_app(app)
    migrate = Migrate(app, db)
    jwt.init_app(app)
    configure_uploads(app, image_set)
    patch_request_class(app, 10 * 1024 * 1024)
    cache.init_app(app)
    limiter.init_app(app)

    @jwt.token_in_blocklist_loader
    def check_if_token_in_blacklist(jwt_header, jwt_payload):
        jti = jwt_payload['jti']
        return jti in black_list

    @app.before_request
    def before_request():
        print('\n=============BEFORE REQUEST===============\n')
        print(cache.cache._cache.keys())
        print('\n==========================================\n')

    @app.after_request
    def after_request(response):
        print('\n============AFTER REQUEST=================\n')
        print(cache.cache._cache.keys())
        print('\n==========================================\n')
        return response

    @limiter.request_filter
    def ip_whitelist():
        return request.remote_addr == '127.0.0.1'
Exemple #8
0
def init_extensions(app):
    db.init_app(app)
    db.app = app
    db.metadata.naming_convention = {
        "ix": 'ix_%(column_0_label)s',
        "uq": "uq_%(table_name)s_%(column_0_name)s",
        "ck": "ck_%(table_name)s_%(column_0_name)s",
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
        "pk": "pk_%(table_name)s"
    }
    # set constraint naming convention to sensible default, per
    # http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#configuring-constraint-naming-conventions

    assets.init_app(app)
    assets.app = app
    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    store.init_app(app)
    rest.init_app(app,
                  flask_sqlalchemy_db=db,
                  preprocessors=restless_preprocessors)
    rest.app = app

    if app.config.get('DEBUG'):
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
Exemple #9
0
def create_app(object_name, env="dev"):
    """
    Arguments:
        object_name: the python path of the config object,
                     e.g. webapp.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)
    app.config['ENV'] = env

    # init the cache
    cache.init_app(app)

    # init SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # register our blueprints
    from controllers.main import main
    from controllers.user import user
    app.register_blueprint(main)
    app.register_blueprint(user)

    return app
Exemple #10
0
def configure_app(app, config=None):
    """Different ways of configurations."""

    # http://flask.pocoo.org/docs/api/#configuration
    app.config.from_object(DefaultConfig)

    # http://flask.pocoo.org/docs/config/#instance-folders
    app.config.from_pyfile('prod.py', silent=True)

    if config:
        app.config.from_object(config)
        
    # Use instance folder instead of env variables to make deployment easier.
    #app.config.from_envvar('%s_APP_CONFIG' % DefaultConfig.PROJECT.upper(), silent=True)

    #Redis Cache
    cache_config = {
        'CACHE_TYPE': DefaultConfig.CACHE_TYPE,
        'CACHE_REDIS_HOST': DefaultConfig.CACHE_REDIS_HOST,
        'CACHE_REDIS_PORT': DefaultConfig.CACHE_REDIS_PORT,
        'CACHE_REDIS_DB': DefaultConfig.CACHE_REDIS_DB,
        'CACHE_REDIS_PASSWORD': DefaultConfig.CACHE_REDIS_PASSWORD
                    }

    cache.init_app(app, config=cache_config)
    RedisSession(app)
    socketio = SocketIO(app, async_mode='eventlet', message_queue=app.config['SOCKETIO_REDIS_URL'])  
    socketio.on_namespace(Socket_conn('/deyunio'))
def register_extensions(app):
    db.init_app(app)
    migrate = Migrate(app, db)
    jwt.init_app(app)
    configure_uploads(app, image_set)
    patch_request_class(app, 10 * 1024 * 1024)
    cache.init_app(app)
    limiter.init_app(app)

    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(decrypted_token):
        jti = decrypted_token['jti']
        return jti in black_list

    @app.before_request
    def before_request():
        print('\n==================== BEFORE REQUEST ====================\n')
        print(cache.cache._cache.keys())
        print('\n=======================================================\n')

    @app.after_request
    def after_request(response):
        print('\n==================== AFTER REQUEST ====================\n')
        print(cache.cache._cache.keys())
        print('\n=======================================================\n')
        return response
Exemple #12
0
def configure_extensions(app):
    db.app = app
    celery.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    cache.init_app(app)
    celery.init_app(app)
Exemple #13
0
def register_extensions(app):
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    return None
def register_extensions(app):
    cache.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    register_admin_views(admin)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore, confirm_register_form=ExtendedRegisterForm)
    mail.init_app(app)
    debug_toolbar.init_app(app)

    return None
Exemple #15
0
def create_app(config_name, production=False):
    """
    工厂方法创建 Web App
    :param config_name: 从config中加载一个配置类
    :param production: 只有服务器部署时候设置为True,会加载instance下的config.py
    :return: app
    """
    app = Flask(__name__, instance_relative_config=production)
    app.config.from_object(config_name)
    app.config.from_pyfile('config.py', silent=True)

    csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    principal.init_app(app)
    cache.init_app(app)
    configure_uploads(app, photos)
    patch_request_class(app, 64 * 1024 * 1024)
    assets_env.init_app(app)
    assets_env.register('main_css', main_css)
    assets_env.register('main_js', main_js)
    assets_env.register('main_js_ie8', main_js_ie8)
    assets_env.register('admin_css', admin_css)
    assets_env.register('admin_js', admin_js)
    assets_env.register('admin_js_ie8', admin_js_ie8)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user
        g.user = current_user
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint)

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint)

    @app.template_test('current_link')
    def is_current_link(link):
        return link == request.path

    return app
Exemple #16
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    flask_static_digest.init_app(app)
    return None
Exemple #17
0
def register_extensions(app):
    cache.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    register_admin_views(admin)
    user_datastore = MongoEngineUserDatastore(db, User, Role)
    security = Security(app, user_datastore, confirm_register_form=ExtendedRegisterForm)
    mail.init_app(app)
    debug_toolbar.init_app(app)

    return None
Exemple #18
0
def register_extensions(app):
    db.init_app(app)
    migrate = Migrate(app, db)
    jwt.init_app(app)
    configure_uploads(app, image_set)
    patch_request_class(app, 10 * 1024 * 1024)
    cache.init_app(app)
    limiter.init_app(app)

    @jwt.token_in_blacklist_loader
    def check_if_token_in_black(decrypted_token):
        jti = decrypted_token['jti']
        return jti in black_list
def configure_extensions(app):

    configure_assets(app)
    bcrypt.init_app(app)
    babel.init_app(app)
    cache.init_app(app)
    celery = Celery(app)
    mail.init_app(app)
    mongodb.init_app(app)
    sqldb.init_app(app)

    if app.debug:
        debugtoolbar = DebugToolbarExtension(app)
def get_app(config=None, **kwargs):
    """Creates a Flask application"""
    app = Flask(__name__, **kwargs)

    configure_app(app, config)

    init_engine(app.config['DATABASE_URI'])

    cache.init_app(app)

    configure_logging(app)

    return app
Exemple #21
0
def init_extensions(app):
    db.init_app(app)
    db.app = app
    db.metadata.naming_convention = {
        "ix": 'ix_%(column_0_label)s',
        "uq": "uq_%(table_name)s_%(column_0_name)s",
        "ck": "ck_%(table_name)s_%(column_0_name)s",
        "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
        "pk": "pk_%(table_name)s"
    }
    # set constraint naming convention to sensible default, per
    # http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#configuring-constraint-naming-conventions

    assets.init_app(app)
    assets.app = app
    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    rq.init_app(app)
    app.rq = rq
    store.init_app(app)
    rest.init_app(app,
                  flask_sqlalchemy_db=db,
                  preprocessors=restless_preprocessors)
    rest.app = app

    limiter.init_app(app)
    for handler in app.logger.handlers:
        limiter.logger.addHandler(handler)

    # stable list of admin phone numbers, cached in memory to avoid db hit for each call
    # disable in testing
    if app.config.get('TESTING', False):
        app.ADMIN_PHONES_LIST = []
    else:
        try:
            app.ADMIN_PHONES_LIST = filter(bool, [
                str(u.phone.national_number) if u.phone else None
                for u in User.query.all()
            ])
        except sqlalchemy.exc.SQLAlchemyError:
            # this may throw an error when creating the database from scratch
            pass

    if app.config.get('DEBUG'):
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
        app.debug = True
Exemple #22
0
def config_app(app, config):
    app.logger.info('Setting up application...')

    app.logger.info('Loading config file: %s' % config)
    app.config.from_pyfile(config)

    app.logger.info('Setting up extensions...')
    db.init_app(app)
    # Init the Flask-Bcrypt via app object
    bcrypt.init_app(app)

    # Init the Flask-Login via app object
    login_manager.init_app(app)
    # Init the Flask-Prinicpal via app object
    principals.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        """Change the role via add the Need object into Role.

           Need the access the app object.
        """

        # Set the identity user object
        identity.user = current_user

        # Add the UserNeed to the identity user object
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        # Add each role to the identity user object
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))
    # 自定义全局函数
    app.add_template_global(admin_permission, 'admin_permission')
    app.add_template_global(app.config.get('VERSION_NO'), 'version_no')

    # Init the Flask-Cache via app object
    cache.init_app(app)


    @app.after_request
    def after_request(response):
        try:
            db.session.commit()
        except Exception:
            db.session.rollback()
            abort(500)
        return response
Exemple #23
0
def configure_extensions(app):
    # flask-mongoengine
    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)
    # flask-mail
    mail.init_app(app)

    # flask-babel
    babel.init_app(app)

    # Bcrypt for hashing passwords
    bcrypt.init_app(app)

    # the Gravatar service
    gravatar.init_app(app)

    # Markdown
    md.init_app(app)

    # Caching
    cache.init_app(app)

    # Debug Toolbar
    if app.debug:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)

    @babel.localeselector
    def get_locale():
        """
        Get the current request locale.

        returns String

        """
        if not hasattr(g, 'lang'):
            g.lang = 'en'
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        return g.lang or request.accept_languages.best_match(accept_languages)

    # flask-login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()

    login_manager.setup_app(app)
Exemple #24
0
def configure_extensions(app):
    # flask-mongoengine
    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)
    # flask-mail
    mail.init_app(app)

    # flask-babel
    babel.init_app(app)

    # Bcrypt for hashing passwords
    bcrypt.init_app(app)

    # the Gravatar service
    gravatar.init_app(app)

    # Markdown
    md.init_app(app)

    # Caching
    cache.init_app(app)

    # Debug Toolbar
    if app.debug:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)

    @babel.localeselector
    def get_locale():
        """
        Get the current request locale.

        returns String

        """
        if not hasattr(g, 'lang'):
            g.lang = 'en'
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        return g.lang or request.accept_languages.best_match(accept_languages)

    # flask-login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()

    login_manager.setup_app(app)
Exemple #25
0
def create_app(environment='DEVELOPMENT'):
    if os.environ.get("ATOM_SETTINGS") == "PRODUCTION":
        environment = "PRODUCTION"

    app = Flask(__name__)
    app.config.from_object(config[environment])
    db.init_app(app)
    cache.init_app(app)

    from packages import packages
    app.register_blueprint(packages, url_prefix='/api/packages')
    create_restless_api(app)

    # Register views
    register_views(app)
    return app
Exemple #26
0
def create_app(config=None):
    app = Flask(__name__)

    if config is None:
        if getenv('PROD') == '1':
            config = ProdConfig
        else:
            config = DevConfig

    app.config.from_object(config)
    cache.init_app(app, config=config.CACHE_CONFIG)
    db.init_app(app)

    register_blueprints(app)

    return app
Exemple #27
0
def configure_extensions(app):

    from extensions import cache, db, mail, Login 

    # initialize mail
    mail = mail.init_app(app)

    # initialize cache
    cache = cache.init_app(app)

    # initialize database
    db.init_app(app)
    app.logger.info("Database initialized.")
    db.app = app
    db.metadata.bind = db.get_engine(app)
    db.metadata.reflect()
    app.logger.info("Database tables reflected.")
    from models import User
    db.create_all(bind=['users'])

    # login
    Login.manager.setup_app(app)
    @Login.manager.user_loader
    def load_user(userid):
        return User.query.get(userid)

    @Login.manager.token_loader
    def load_token(token):
        return User.query.filter(User.passkey == token).first()
Exemple #28
0
def create_app(environment='DEVELOPMENT'):
    if os.environ.get("ATOM_SETTINGS") == "PRODUCTION":
        environment = "PRODUCTION"

    app = Flask(__name__)
    app.config.from_object(config[environment])
    db.init_app(app)
    cache.init_app(app)

    from packages import packages
    app.register_blueprint(packages, url_prefix='/api/packages')
    create_restless_api(app)

    # Register views
    register_views(app)
    return app
Exemple #29
0
def register_extensions(app):
    """function to initialize extensions"""
    db.app = app
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    configure_uploads(app, image_set)
    patch_request_class(app, 10*1024*1024)
    cache.init_app(app)
    limiter.init_app(app)

    # check whether the token is on the blacklist
    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(decrypted_token):
        jti = decrypted_token['jti']

        return jti in black_list
Exemple #30
0
def register_extensions(app):
    db.init_app(app)
    migrate = Migrate(app, db)
    jwt.init_app(app)
    configure_uploads(app, image_set)
    patch_request_class(app, 4 * 1024 * 1024)
    cache.init_app(app)
    limiter.init_app(app)

    @limiter.request_filter
    def ip_whitelist():
        return request.remote_addr == '127.0.0.1'

    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(decrypted_token):
        jti = decrypted_token['jti']
        return jti in blacklist
Exemple #31
0
def create_app():
    application = Flask(__name__)
    application.config.update(settings)

    mail.init_app(application)
    mongo.init_app(application)
    cache.init_app(application)
    jwt.init_app(application)
    limiter.init_app(application)

    for bp in http_blueprints:
        import_module(bp.import_name)
        application.register_blueprint(bp)

    application.cli.add_command(populate_users_command)
    application.cli.add_command(populate_transactions_command)

    return application
Exemple #32
0
    def register_extensions(self):
        cache.init_app(self)
        db.init_app(self)
        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        security = Security(self, user_datastore, register_form=ExtendedRegisterForm)
        mail.init_app(self)
        debug_toolbar.init_app(self)
        migrate.init_app(self, db)
        admin.init_app(self)

        @security.context_processor
        def security_context_processor():
            return dict(
                admin_base_template=admin.base_template,
                admin_view=admin.index_view,
                # h=admin_helpers,
                get_url=url_for
            )
Exemple #33
0
def register_extensions(app):
    cache.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    register_admin_views(admin)
    user_datastore = MongoEngineUserDatastore(db, User, Role)
    security = Security(app, user_datastore, register_form=ExtendedRegisterForm)
    mail.init_app(app)
    # socketio.init_app(app)
    app.config['DEBUG_TB_PANELS'] = ['flask.ext.mongoengine.panels.MongoDebugPanel',
                                     'flask_debugtoolbar.panels.versions.VersionDebugPanel',
                                     'flask_debugtoolbar.panels.timer.TimerDebugPanel',
                                     'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
                                     'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
                                     'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
                                     'flask_debugtoolbar.panels.template.TemplateDebugPanel',
                                     'flask_debugtoolbar.panels.logger.LoggingPanel',
                                     'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel']
    debug_toolbar.init_app(app)

    return None
Exemple #34
0
def configure_extensions(app):
    # flask-babel
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        return request.accept_languages.best_match(accept_languages)

    # flask-sqlalchemy
    db.init_app(app)

    # flask-mail
    mail.init_app(app)

    #mongo db
    mongo.init_app(app)

    # flask-cache
    cache.init_app(app)

    # flask-login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(id)
    login_manager.init_app(app)

    # flask-openid
    oid.init_app(app)

    # init debug toolbar
    toolbar = DebugToolbarExtension(app)

    init_extensions(app)
Exemple #35
0
def configure_extensions(app):
    # flask-mongoengine
    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)
    # flask-mail
    mail.init_app(app)

    # flask-babel
    babel.init_app(app)

    # Bcrypt for hashing passwords
    bcrypt.init_app(app)

    # the Gravatar service
    gravatar.init_app(app)

    # Markdown
    md.init_app(app)

    # Caching
    cache.init_app(app)

    # Debug Toolbar
    if app.debug and app.config['DEBUG_TB_PROFILER_ENABLED']:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)

    @babel.localeselector
    def get_locale():
        """
        Get the current request locale.

        returns String

        """
        if not hasattr(g, 'lang'):
            g.lang = app.config.get('BABEL_DEFAULT_LOCALE')
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        # Try to guess the language from the user accept
        # header the browser transmits. We support ar/fr/en,
        # The best match wins.

        g.lang = session.get('language', None) or \
            request.accept_languages.best_match(accept_languages) or \
            g.lang

        if g.lang == 'ar':
            g.lang_dir = 'rtl'
            g.layout_dir_class = 'right-to-left'
            g.language_name = u'العربية'
        else:
            g.lang_dir = 'ltr'
            g.layout_dir_class = 'left-to-right'
            g.language_name = 'English' if g.lang == 'en' else u'Français'

        return g.lang

    # flask-login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()

    login_manager.setup_app(app)
Exemple #36
0
from flask import Flask
import api
from flasgger import Swagger, swag_from
from flask_cors import CORS
import os
from extensions import cache
import numpy as np
import scipy

app = Flask(__name__)
app.config.from_object('config')
CORS(app, supports_credentials=True)
swagger = Swagger(app, template_file=os.path.join(os.getcwd(), 'api', 'resources', 'template.yaml'))
app.register_blueprint(api.views.blueprint)
cache.init_app(app)

if __name__ == '__main__':

    app.run()
Exemple #37
0
def extensions_fabrics(app):
    db.init_app(app)
    cache.init_app(app)
    admin = ModelViewAdministrator(app)
Exemple #38
0
def configure_extensions(app):
    """配置拓展程序,数据库db、缓存cache、邮件mail"""
    # configure extensions         
    db.init_app(app)
    cache.init_app(app)
    mail.init_app(app)
Exemple #39
0
def configure_extensions(app):
    # flask-mongoengine
    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)
    # flask-mail
    mail.init_app(app)

    # flask-babel
    babel.init_app(app)

    # Bcrypt for hashing passwords
    bcrypt.init_app(app)

    # the Gravatar service
    gravatar.init_app(app)

    # Markdown
    md.init_app(app)

    # Caching
    cache.init_app(app)

    # Debug Toolbar
    if app.debug and app.config['DEBUG_TB_PROFILER_ENABLED']:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)

    @babel.localeselector
    def get_locale():
        """
        Get the current request locale.

        returns String

        """
        if not hasattr(g, 'lang'):
            g.lang = app.config.get('BABEL_DEFAULT_LOCALE')
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        # Try to guess the language from the user accept
        # header the browser transmits. We support ar/fr/en,
        # The best match wins.

        g.lang = session.get('language', None) or \
            request.accept_languages.best_match(accept_languages) or \
            g.lang

        if g.lang == 'ar':
            g.lang_dir = 'rtl'
            g.layout_dir_class = 'right-to-left'
            g.language_name = u'العربية'
        else:
            g.lang_dir = 'ltr'
            g.layout_dir_class = 'left-to-right'
            g.language_name = 'English' if g.lang == 'en' else u'Français'

        return g.lang

    # flask-login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()

    login_manager.setup_app(app)
def create_app(name=None, config=None):
    effective_name = name if name else __name__
    app = Flask(
        effective_name,
        template_folder=os.path.join(FLASK_APP_DIR, '..', 'templates'),
        static_folder=os.path.join(FLASK_APP_DIR, '..', 'static')
    )

    #  Config
    effective_config = config or 'flask_application.config.app_config'
    app.config.from_object(effective_config)
    app.logger.info("Config: %s; DB: %s" % (app.config['ENVIRONMENT'], app.config['SQLALCHEMY_DATABASE_URI']))

    #  Logging
    import logging
    logging.basicConfig(
        level=app.config['LOG_LEVEL'],
        format='%(asctime)s %(levelname)s: %(message)s '
               '[in %(pathname)s:%(lineno)d]',
        datefmt='%Y%m%d-%H:%M%p',
    )

    #  Email on errors
    if not app.debug:
        import logging.handlers
        mail_handler = logging.handlers.SMTPHandler(
            'localhost',
            os.getenv('USER'),
            app.config['SYS_ADMINS'],
            '{0} error'.format(app.config['SITE_NAME']),
        )
        mail_handler.setFormatter(logging.Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''.strip()))
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
        app.logger.info("Emailing on error is ENABLED")
    else:
        app.logger.info("Emailing on error is DISABLED")

    # Bootstrap
    from flask_bootstrap import Bootstrap
    Bootstrap(app)

    # Assets
    from flask.ext.assets import Environment
    app.assets = Environment(app)
    # Ensure output directory exists
    assets_output_dir = os.path.join(FLASK_APP_DIR, '..', 'static', 'gen')
    if not os.path.exists(assets_output_dir):
        os.mkdir(assets_output_dir)

    # Email
    mail.init_app(app)
    app.mail = mail

    # Memcache
    cache.init_app(app)
    app.cache = cache

    # Business Logic
    # http://flask.pocoo.org/docs/patterns/packages/
    # http://flask.pocoo.org/docs/blueprints/
    from flask_application.controllers.frontend import frontend
    app.register_blueprint(frontend)

    # SQLAlchemy
    db.init_app(app)
    app.db = db

    from flask.ext.security import SQLAlchemyUserDatastore
    from flask_application.models import User, Role
    from flask_application.ext.flask_security import ExtendedLoginForm

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    app.user_datastore = user_datastore

    security.init_app(app=app, datastore=user_datastore, login_form=ExtendedLoginForm)
    app.security = security


    from flask_application.controllers.admin import admin
    app.register_blueprint(admin)

    # REST
    from flask.ext.restful import Api
    app.api = Api(app)

    # TODO
    from flask_application.controllers.todo import todo_blueprint
    app.register_blueprint(todo_blueprint)

    from flask_application.controllers.todo import TodoResource
    app.api.add_resource(TodoResource, '/api/todo', '/api/todo/<int:todo_id>')

    from werkzeug.contrib.fixers import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    if app.config['SETUP_DB']:
        with app.app_context():
            app.db.drop_all()
            app.db.create_all()

            from flask_application.populate import populate_data
            populate_data(app)

    return app
Exemple #41
0
def create_app(config_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/
    Arguments:
        config_name: the key value if the config.config dict,
                     e.g. 'dev', 'test', 'product', 'default'
    """

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    # 首先调用配置对象的init_app
    config[config_name].init_app(app)

    # init SQLAlchemy
    db.init_app(app)
    # init Bcrypt
    bcrypt.init_app(app)
    # init LoginManager
    login_manager.init_app(app)
    # init Principal
    principal.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        # Set the identity user object
        identity.user = current_user
        # Add the UserNeed to the identity
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))
        # Add each role to the identity
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    # init DebugToolbarExtension
    debug_toolbar.init_app(app)

    # init Cache
    cache.init_app(app)

    # init Flask-Assets
    assets_env.init_app(app)
    assets_env.register("main_css", main_css)
    assets_env.register("main_js", main_js)

    # init Flask-Admin
    admin.init_app(app)
    admin.add_view(CustomView(name='Custom'))

    models = [User, Role, Comment, Tag]
    for model in models:
        admin.add_view(CustomModelView(model, db.session, category='Models'))
    # 单独处理Post model,因为我们自定了CustomModelView的自类PostView
    admin.add_view(PostView(Post, db.session, category='Models'))

    admin.add_view(CustomFileAdmin(
        os.path.join(os.path.dirname(__file__), 'static'),
        '/static/',
        name='Static Files'
    ))

    # init Flask-Bootstrap
    bootstrap.init_app(app)

    # init Flask-Mail
    mail.init_app(app)

    # init Flask-Moment
    moment.init_app(app)

    ############################################################################

    # init RestApi
    rest_api.add_resource(PostApi, '/api/post', '/api/post/<int:post_id>',
                          endpoint='api')
    rest_api.add_resource(AuthApi, '/api/auth')
    rest_api.init_app(app)

    # register blueprint
    app.register_blueprint(blog_blueprint)
    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint)
    # register api blueprint
    app.register_blueprint(api_blueprint)

    return app
Exemple #42
0
def create_app():
    app = Flask(__name__)
    app.register_blueprint(main)
    cache.init_app(app)
    return app
# Model stuff
from model.fit import fit_to_model

# ==============================================================================
# Initiatlize
# ==============================================================================

app = Flask(__name__)
api = Api(app)
app.config['SECRET_KEY'] = 'any secret string'
csrf = CSRFProtect(app)

# Initialize the cache
cache.init_app(app=app,
               config={
                   "CACHE_TYPE": "filesystem",
                   'CACHE_DIR': '/tmp'
               })

# Initialize args
parser = reqparse.RequestParser()

# Configure args per endpoint
# parser.add_argument('data', type=str, required=True, help='Data to be fitted')

# ==============================================================================
# QA Test
# ==============================================================================

# If current model isn't loaded, load it
model_path = Path("data/tmp/best_model.pkl")