示例#1
0
文件: app.py 项目: kaigezhang/pdano
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
示例#2
0
def register_extensions(app):
    from server.extensions import (
        db,
        migrate,
        mail,
        babel,
        cors,
        jwt,
        cache,
        compress,
        swagger,
    )

    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    babel.init_app(app)

    cors.init_app(
        app, resources={r"/api/*": {"origins": "*"}}, supports_credentials=True
    )
    jwt.init_app(app)
    cache.init_app(app)
    compress.init_app(app)
    swagger.init_app(app)

    # Return validation errors as JSON
    @app.errorhandler(422)
    @app.errorhandler(400)
    def handle_error(err):
        messages = err.data.get("messages", "Invalid request.")
        return jsonify({"message": messages["json"]}), 400
示例#3
0
def create_app(object_name, env="prod"):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. server.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
    cors = CORS(app)
    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    return app
示例#4
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. server.settings.ProdConfig

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

    app = Flask(__name__)

    app.config.from_object(object_name)

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    return app
示例#5
0
def register_extensions(app, testing=False):

    jwt.init_app(app)
    cors.init_app(app)
    cache.init_app(app)
    api.init_app(app)
示例#6
0
def setup_extensions(app):
    db.init_app(app)
    cache.init_app(app)
    bcrypt.init_app(app)
    cors.init_app(app)
    setup_logger(app)
示例#7
0
def create_app(default_config_path=None):
    """Create and return a Flask application. Reads a config file path from the
    OK_SERVER_CONFIG environment variable. If it is not set, reads from
    default_config_path instead. This is so we can default to a development
    environment locally, but the app will fail in production if there is no
    config file rather than dangerously defaulting to a development environment.
    """

    app = Flask(__name__)

    config_path = os.getenv('OK_SERVER_CONFIG', default_config_path)
    if config_path is None:
        raise ValueError('No configuration file found'
            'Check that the OK_SERVER_CONFIG environment variable is set.')
    app.config.from_pyfile(config_path)

    # Set REMOTE_ADDR for proxies
    num_proxies = app.config.get('NUM_PROXIES', 0)
    if num_proxies:
        app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=num_proxies)

    # Sentry Error Reporting
    sentry_dsn = os.getenv('SENTRY_DSN')
    if not app.debug and sentry_dsn:
        sentry.init_app(app, dsn=sentry_dsn)

        @app.errorhandler(500)
        def internal_server_error(error):
            return render_template('errors/500.html',
                event_id=g.sentry_event_id,
                public_dsn=sentry.client.get_public_dsn('https')
            ), 500

    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith("/api"):
            return api.handle_error(error)
        return render_template('errors/404.html'), 404

    @app.route("/healthz")
    def health_check():
        return 'OK'

    # initialize the cache
    cache.init_app(app)

    # initialize redis task queues
    RQ(app)

    # Protect All Routes from csrf
    csrf.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)


    # Flask-Login manager
    login_manager.init_app(app)

    # Set up logging
    logging.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # custom URL handling
    converters.init_app(app)

    # custom Jinja rendering
    app.jinja_env.globals.update({
        'utils': utils,
        'debug': app.debug,
        'instantclick': app.config.get('INSTANTCLICK', True),
        'CSRFForm': CSRFForm
    })

    app.jinja_env.filters.update({
        'markdown': utils.convert_markdown,
        'pluralize': utils.pluralize,
    })

    # register our blueprints
    # OAuth should not need CSRF protection
    csrf.exempt(auth)
    app.register_blueprint(auth)

    csrf.exempt(oauth)
    app.register_blueprint(oauth)

    app.register_blueprint(student)

    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(about, url_prefix='/about')

    # Redis Queue dashboard
    csrf.exempt(queue)
    app.register_blueprint(queue, url_prefix='/rq')

    # API does not need CSRF protection
    csrf.exempt(api_endpoints)
    app.register_blueprint(api_endpoints, url_prefix=API_PREFIX)

    return app
示例#8
0
def create_app(default_config_path=None):
    """Create and return a Flask application. Reads a config file path from the
    OK_SERVER_CONFIG environment variable. If it is not set, reads from
    default_config_path instead. This is so we can default to a development
    environment locally, but the app will fail in production if there is no
    config file rather than dangerously defaulting to a development environment.
    """

    app = Flask(__name__)

    config_path = os.getenv('OK_SERVER_CONFIG', default_config_path)
    if config_path is None:
        raise ValueError(
            'No configuration file found'
            'Check that the OK_SERVER_CONFIG environment variable is set.')
    app.config.from_pyfile(config_path)

    # Senty Error Reporting & Other Prod Changes
    sentry_dsn = os.getenv('SENTRY_DSN')
    if not app.debug:
        app.wsgi_app = ProxyFix(app.wsgi_app)
        if sentry_dsn:
            sentry.init_app(app, dsn=sentry_dsn)

            @app.errorhandler(500)
            def internal_server_error(error):
                return render_template(
                    'errors/500.html',
                    event_id=g.sentry_event_id,
                    public_dsn=sentry.client.get_public_dsn('https')), 500

        # In production mode, add log handler to sys.stderr.
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.INFO)

    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith("/api"):
            return api.handle_error(error)
        return render_template('errors/404.html'), 404

    # initialize the cache
    cache.init_app(app)

    # initialize redis task queues
    RQ(app)

    # Protect All Routes from csrf
    csrf.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    # Flask-Login manager
    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # custom URL handling
    converters.init_app(app)

    # custom Jinja rendering
    app.jinja_env.globals.update({
        'utils':
        utils,
        'debug':
        app.debug,
        'instantclick':
        app.config.get('INSTANTCLICK', True),
        'CSRFForm':
        CSRFForm
    })

    app.jinja_env.filters.update({
        'markdown': utils.convert_markdown,
        'pluralize': utils.pluralize,
    })

    # register our blueprints
    # OAuth should not need CSRF protection
    csrf.exempt(auth)
    app.register_blueprint(auth)

    csrf.exempt(oauth)
    app.register_blueprint(oauth)

    app.register_blueprint(student)

    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(about, url_prefix='/about')

    # Redis Queue dashboard
    csrf.exempt(queue)
    app.register_blueprint(queue, url_prefix='/rq')

    # API does not need CSRF protection
    csrf.exempt(api_endpoints)
    app.register_blueprint(api_endpoints, url_prefix=API_PREFIX)

    return app
示例#9
0
def create_app(environment_name=None):
    """Create and return a Flask application. Reads a config file path from the
    OK_SERVER_CONFIG environment variable. If it is not set, it imports and reads 
    from the config module (using environment_name). This is so we can default to a development
    environment locally, but the app will fail in production if there is no
    config file rather than dangerously defaulting to a development environment.
    """

    app = Flask(__name__)

    env_module_path = os.getenv('OK_SERVER_CONFIG',
                                'server.settings.{}'.format(environment_name))

    if '/' in env_module_path:
        env_module_path = env_module_path.replace('/', '.')
        env_module_path = env_module_path.replace('.py', '')

    app.config.from_object(env_module_path  + '.Config')

    # Set REMOTE_ADDR for proxies
    num_proxies = app.config.get('NUM_PROXIES', 0)
    if num_proxies:
        app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=num_proxies)

    # Sentry Error Reporting
    sentry_dsn = os.getenv('SENTRY_DSN')
    if not app.debug and sentry_dsn:
        sentry.init_app(app, dsn=sentry_dsn)

        @app.errorhandler(500)
        def internal_server_error(error):
            return render_template('errors/500.html',
                event_id=g.sentry_event_id,
                public_dsn=sentry.client.get_public_dsn('https')
            ), 500

    # Azure Application Insights request and error tracking
    appinsights.init_app(app)

    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith("/api"):
            return api.handle_error(error)
        return render_template('errors/404.html'), 404

    @app.route("/healthz")
    def health_check():
        return 'OK'

    @app.after_request
    def flush_appinsights_telemetry(response):
        appinsights.flush()
        return response

    @app.context_processor
    def inject_root_url():
        return {'index_url': app.config['APPLICATION_ROOT']}

    # initialize the cache
    cache.init_app(app)

    # initialize redis task queues
    RQ(app)

    # Protect All Routes from csrf
    csrf.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    # Flask-Login manager
    login_manager.init_app(app)

    # initalize cloud storage
    storage.init_app(app)
    # Set up logging
    logging.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # custom URL handling
    converters.init_app(app)

    # custom Jinja rendering
    app.jinja_env.globals.update({
        'utils': utils,
        'debug': app.debug,
        'instantclick': app.config.get('INSTANTCLICK', True),
        'CSRFForm': CSRFForm
    })

    app.jinja_env.filters.update({
        'markdown': utils.convert_markdown,
        'pluralize': utils.pluralize,
    })

    # register our blueprints
    # OAuth should not need CSRF protection
    csrf.exempt(auth)
    app.register_blueprint(auth)

    csrf.exempt(oauth)
    app.register_blueprint(oauth)
    app.register_blueprint(files)

    app.register_blueprint(student)

    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(about, url_prefix='/about')

    # Redis Queue dashboard
    csrf.exempt(queue)
    app.register_blueprint(queue, url_prefix='/rq')

    # API does not need CSRF protection
    csrf.exempt(api_endpoints)
    app.register_blueprint(api_endpoints, url_prefix=API_PREFIX)

    return app