Example #1
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(settings)

    DB.init_app(app)
    redis_store.init_app(app)
    routes.configure_routes(app)
    configure_login(app)
    configure_logger(app)

    app.register_error_handler(400, error_400)
    app.register_error_handler(404, error_404)
    app.register_error_handler(405, error_405)
    app.register_error_handler(Exception, exception_handler)

    app.jinja_env.filters["json"] = json.dumps

    def epoch_to_date(s):
        import datetime

        return datetime.datetime.fromtimestamp(s).strftime("%B %-d, %Y")

    def epoch_to_ts(s):
        import datetime

        return datetime.datetime.fromtimestamp(s).strftime("%m-%-d-%Y %H:%M")

    app.jinja_env.filters["epoch_to_date"] = epoch_to_date
    app.jinja_env.filters["epoch_to_ts"] = epoch_to_ts
    app.config["CDN_DOMAIN"] = os.getenv(
        "CDN_DOMAIN", re.sub("https?://", "", settings.SERVICE_URL)
    )
    app.config["CDN_HTTPS"] = True
    cdn.init_app(app)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            if app.config["TESTING"]:
                # When testing, celery tasks are called eagerly, from the same thread
                # so don't push an app context, the request's app context is already there
                return self.run(*args, **kwargs)
            else:
                with app.app_context():
                    g.log = structlog.get_logger().new()
                    return self.run(*args, **kwargs)

    celery.Task = ContextTask

    if not app.debug and not app.testing:
        configure_ssl_redirect(app)

    Limiter(
        app,
        key_func=get_ipaddr,
        global_limits=[settings.RATE_LIMIT],
        storage_uri=settings.REDIS_RATE_LIMIT,
    )

    return app