Example #1
0
def register_extensions(app):

    debug_toolbar.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    mail.init_app(app)
    api.init_app(app)
    jwt.init_app(app)
    limiter.init_app(app)
Example #2
0
def register_extensions(app):
    """Register extensions with the Flask application."""
    travis.init_app(app)
    db.init_app(app)
    lm.init_app(app)
    mail.init_app(app)
    bcrypt.init_app(app)
    assets.init_app(app)
    babel.init_app(app)
    rq.init_app(app)
    migrate.init_app(app, db)
    limiter.init_app(app)
def register_extensions(app: flask.Flask) -> None:
    app.secret_key = APP_SESSION_SECRET

    db.init_app(app)
    migrate.init_app(app, db)
    cache.init_app(app, config={'CACHE_TYPE': CACHE_TYPE, 'CACHE_THRESHOLD': CACHE_THRESHOLD})
    limiter.init_app(app)
    session.init_app(app)
    oauth.init_app(app)

    trace_flask(app, operation_name=get_operation_name, skip_span=request_skip_span)
    trace_sqlalchemy(skip_span=sqlalchemy_skip_span)
Example #4
0
def register_extensions(app):
    """Register extensions with the Flask application."""
    travis.init_app(app)
    db.init_app(app)
    lm.init_app(app)
    mail.init_app(app)
    bcrypt.init_app(app)
    assets.init_app(app)
    babel.init_app(app)
    rq.init_app(app)
    migrate.init_app(app, db)
    limiter.init_app(app)
Example #5
0
def create_app() -> Flask:
    app = Flask(__name__)
    # SimpleLogin is deployed behind NGINX
    app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
    limiter.init_app(app)

    app.url_map.strict_slashes = False

    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # enable to print all queries generated by sqlalchemy
    # app.config["SQLALCHEMY_ECHO"] = True

    app.secret_key = FLASK_SECRET

    app.config["TEMPLATES_AUTO_RELOAD"] = True

    # to avoid conflict with other cookie
    app.config["SESSION_COOKIE_NAME"] = "slapp"
    if URL.startswith("https"):
        app.config["SESSION_COOKIE_SECURE"] = True
    app.config["SESSION_COOKIE_SAMESITE"] = "Lax"

    setup_error_page(app)

    init_extensions(app)
    register_blueprints(app)
    set_index_page(app)
    jinja2_filter(app)

    setup_favicon_route(app)
    setup_openid_metadata(app)

    init_admin(app)
    setup_paddle_callback(app)
    setup_do_not_track(app)

    if FLASK_PROFILER_PATH:
        LOG.d("Enable flask-profiler")
        app.config["flask_profiler"] = {
            "enabled": True,
            "storage": {"engine": "sqlite", "FILE": FLASK_PROFILER_PATH},
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": FLASK_PROFILER_PASSWORD,
            },
            "ignore": ["^/static/.*", "/git", "/exception"],
        }
        flask_profiler.init_app(app)

    return app
Example #6
0
def register_extensions(app: flask.Flask) -> None:
    app.secret_key = APP_SESSION_SECRET

    db.init_app(app)
    migrate.init_app(app, db)
    cache.init_app(app,
                   config={
                       'CACHE_TYPE': CACHE_TYPE,
                       'CACHE_THRESHOLD': CACHE_THRESHOLD
                   })
    limiter.init_app(app)
    session.init_app(app)
    oauth.init_app(app)
Example #7
0
def create_app(config_class=Config):

    app = Flask(__name__)
    # set app configs
    app.config.from_object(config_class)

    # register extensions
    db.init_app(app)
    limiter.init_app(app)
    migrate.init_app(app)
    flask_uuid.init_app(app)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    # register custom errors
    app.register_error_handler(429, handle_429_request)
    app.register_error_handler(405, handle_wrong_method)
    app.register_error_handler(404, handle_not_found)

    # logging stuff
    formatter = logging.Formatter(
        "[%(asctime)s] [%(pathname)s:%(lineno)d] %(levelname)s - %(message)s")
    handler = RotatingFileHandler(app.config['LOG_FILENAME'],
                                  maxBytes=10000000,
                                  backupCount=5)
    log_level = app.config['LOG_LEVEL']

    if log_level == 'DEBUG':  # pragma: no cover
        app.logger.setLevel(logging.DEBUG)  # pragma: no cover
    elif log_level == 'INFO':  # pragma: no cover
        app.logger.setLevel(logging.INFO)  # pragma: no cover
    elif log_level == 'WARNING':  # pragma: no cover
        app.logger.setLevel(logging.WARNING)  # pragma: no cover
    elif log_level == 'ERROR':  # pragma: no cover
        app.logger.setLevel(logging.ERROR)  # pragma: no cover
    else:  # pragma: no cover
        app.logger.setLevel(logging.CRITICAL)  # pragma: no cover

    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

    return app
Example #8
0
def create_app() -> Flask:
    app = Flask(__name__)
    # SimpleLogin is deployed behind NGINX
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)
    limiter.init_app(app)

    app.url_map.strict_slashes = False

    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # enable to print all queries generated by sqlalchemy
    # app.config["SQLALCHEMY_ECHO"] = True

    app.secret_key = FLASK_SECRET

    app.config["TEMPLATES_AUTO_RELOAD"] = True

    # to avoid conflict with other cookie
    app.config["SESSION_COOKIE_NAME"] = SESSION_COOKIE_NAME
    if URL.startswith("https"):
        app.config["SESSION_COOKIE_SECURE"] = True
    app.config["SESSION_COOKIE_SAMESITE"] = "Lax"

    setup_error_page(app)

    init_extensions(app)
    register_blueprints(app)
    set_index_page(app)
    jinja2_filter(app)

    setup_favicon_route(app)
    setup_openid_metadata(app)

    init_admin(app)
    setup_paddle_callback(app)
    setup_coinbase_commerce(app)
    setup_do_not_track(app)

    if FLASK_PROFILER_PATH:
        LOG.d("Enable flask-profiler")
        app.config["flask_profiler"] = {
            "enabled": True,
            "storage": {
                "engine": "sqlite",
                "FILE": FLASK_PROFILER_PATH
            },
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": FLASK_PROFILER_PASSWORD,
            },
            "ignore": ["^/static/.*", "/git", "/exception"],
        }
        flask_profiler.init_app(app)

    # enable CORS on /api endpoints
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    # set session to permanent so user stays signed in after quitting the browser
    # the cookie is valid for 7 days
    @app.before_request
    def make_session_permanent():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(days=7)

    return app
Example #9
0
def create_app():
    global app_created
    if not app_created:
        BlueprintsManager.register(app)
        graphql_views.init_app(app)
    Migrate(app, db)

    app.config.from_object(env('APP_CONFIG',
                               default='config.ProductionConfig'))

    if not app.config['SECRET_KEY']:
        if app.config['PRODUCTION']:
            app.logger.error(
                'SECRET_KEY must be set in .env or environment variables in production'
            )
            exit(1)
        else:
            random_secret = secrets.token_hex()
            app.logger.warning(
                f'Using random secret "{ random_secret }" for development server. '
                'This is NOT recommended. Set proper SECRET_KEY in .env or environment variables'
            )
            app.config['SECRET_KEY'] = random_secret

    db.init_app(app)

    if app.config['CACHING']:
        cache.init_app(app, config={'CACHE_TYPE': 'simple'})
    else:
        cache.init_app(app, config={'CACHE_TYPE': 'null'})

    stripe.api_key = 'SomeStripeKey'
    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'

    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.ERROR)

    # set up jwt
    app.config['JWT_HEADER_TYPE'] = 'JWT'
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)
    app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=365)
    app.config['JWT_ERROR_MESSAGE_KEY'] = 'error'
    app.config['JWT_TOKEN_LOCATION'] = ['cookies', 'headers']
    app.config['JWT_REFRESH_COOKIE_PATH'] = '/v1/auth/token/refresh'
    app.config['JWT_SESSION_COOKIE'] = False
    app.config['JWT_BLACKLIST_ENABLED'] = True
    app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['refresh']
    _jwt = JWTManager(app)
    _jwt.user_loader_callback_loader(jwt_user_loader)
    _jwt.token_in_blacklist_loader(is_token_blacklisted)

    # setup celery
    app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL']
    app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']
    app.config['CELERY_ACCEPT_CONTENT'] = ['json', 'application/text']

    app.config['MAIL_RECORDER'] = MailRecorder(use_env=True)

    CORS(app, resources={r"/*": {"origins": "*"}})
    AuthManager.init_login(app)

    if app.config['TESTING'] and app.config['PROFILE']:
        # Profiling
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])

    # development api
    with app.app_context():
        from app.api.admin_statistics_api.events import event_statistics
        from app.api.auth import auth_routes
        from app.api.custom.attendees import attendee_blueprint
        from app.api.bootstrap import api_v1
        from app.api.celery_tasks import celery_routes
        from app.api.event_copy import event_copy
        from app.api.exports import export_routes
        from app.api.imports import import_routes
        from app.api.uploads import upload_routes
        from app.api.users import user_misc_routes
        from app.api.orders import order_misc_routes
        from app.api.role_invites import role_invites_misc_routes
        from app.api.auth import authorised_blueprint
        from app.api.admin_translations import admin_blueprint
        from app.api.orders import alipay_blueprint
        from app.api.sessions import sessions_blueprint
        from app.api.settings import admin_misc_routes
        from app.api.server_version import info_route
        from app.api.custom.orders import ticket_blueprint
        from app.api.custom.orders import order_blueprint
        from app.api.custom.invoices import event_blueprint
        from app.api.custom.calendars import calendar_routes

        app.register_blueprint(api_v1)
        app.register_blueprint(event_copy)
        app.register_blueprint(upload_routes)
        app.register_blueprint(export_routes)
        app.register_blueprint(import_routes)
        app.register_blueprint(celery_routes)
        app.register_blueprint(auth_routes)
        app.register_blueprint(event_statistics)
        app.register_blueprint(user_misc_routes)
        app.register_blueprint(attendee_blueprint)
        app.register_blueprint(order_misc_routes)
        app.register_blueprint(role_invites_misc_routes)
        app.register_blueprint(authorised_blueprint)
        app.register_blueprint(admin_blueprint)
        app.register_blueprint(alipay_blueprint)
        app.register_blueprint(admin_misc_routes)
        app.register_blueprint(info_route)
        app.register_blueprint(ticket_blueprint)
        app.register_blueprint(order_blueprint)
        app.register_blueprint(event_blueprint)
        app.register_blueprint(sessions_blueprint)
        app.register_blueprint(calendar_routes)

        add_engine_pidguard(db.engine)

        if app.config['SQLALCHEMY_DATABASE_URI'  # pytype: disable=attribute-error
                      ].startswith("sqlite://"):
            sqlite_datetime_fix()

    sa.orm.configure_mappers()

    if app.config['SERVE_STATIC']:
        app.add_url_rule('/static/<path:filename>',
                         endpoint='static',
                         view_func=app.send_static_file)

    # sentry
    if not app_created and 'SENTRY_DSN' in app.config:
        sentry_sdk.init(
            app.config['SENTRY_DSN'],
            integrations=[
                FlaskIntegration(),
                RedisIntegration(),
                CeleryIntegration(),
                SqlalchemyIntegration(),
            ],
            release=app.config['SENTRY_RELEASE_NAME'],
            traces_sample_rate=app.config['SENTRY_TRACES_SAMPLE_RATE'],
        )

    # redis
    redis_store.init_app(app)

    # Initialize Extensions
    shell.init_app(app)
    limiter.init_app(app)

    app_created = True
    return app
Example #10
0
def create_app(config_class=DevelopmentConfig):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    cache.init_app(app)
    auto.init_app(app)
    jwt.init_app(app)
    limiter.init_app(app)

    origins = {
        "origins": [
            "http://127.0.0.1:3000",
            "http://localhost:3000",
            "http://0.0.0.0:3000",
            "https://app-frontend-test-001.azurewebsites.net:80",
            "https://app-frontend-prod-001.azurewebsites.net:80",
            "https://app.climatemind.org:80",
        ]
    }

    CORS(
        app,
        resources={
            r"/refresh": origins,
            r"/login": origins,
            r"/register": origins,
            r"/logout": origins,
            r"/captcha": origins,
        },
        supports_credentials=True,
    )

    with app.app_context():

        from app.auth import bp as auth_bp

        app.register_blueprint(auth_bp)

        from app.errors import bp as errors_bp

        app.register_blueprint(errors_bp)

        from app.subscribe import bp as subscribe_bp

        app.register_blueprint(subscribe_bp)

        from app.feed import bp as feed_bp

        app.register_blueprint(feed_bp)

        from app.myths import bp as myths_bp

        app.register_blueprint(myths_bp)

        from app.solutions import bp as solutions_bp

        app.register_blueprint(solutions_bp)

        from app.scoring import bp as scoring_bp

        app.register_blueprint(scoring_bp)

        from app.questions import bp as questions_bp

        app.register_blueprint(questions_bp)

        from app.personal_values import bp as personal_values_bp

        app.register_blueprint(personal_values_bp)

        from app.documentation import bp as documentation_bp

        app.register_blueprint(documentation_bp)

        from app.post_code import bp as post_code_bp

        app.register_blueprint(post_code_bp)

        from app.session import bp as session_bp

        app.register_blueprint(session_bp)

    return app