Beispiel #1
1
def create_app(name=__name__):
    app = Flask(__name__, static_path="/static")
    load_config(app)
    babel.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    filters.init_app(app)
    register_local_modules(app)

    app.wsgi_app = ProxyFixupHelper(app.wsgi_app)

    # Enable the DebugToolbar
    if app.config["DEBUG_TOOLBAR"]:
        toolbar = DebugToolbarExtension(app)

    # Always attempt to set a BrowserId. At some point this will get used,
    # but let's start setting it now.
    app.wsgi_app = BrowserIdMiddleware(
        app.wsgi_app,
        secret_key=app.config["BROWSER_SECRET_KEY"],
        cookie_name="b",
        cookie_path="/",
        cookie_domain=None,
        cookie_lifetime=86400 * 365 * 10,
        cookie_secure=None,
        vary=(),
    )

    return app
Beispiel #2
1
def make_app(**local_conf):
    """
    Entry point for Elastic Hadoop on OpenStack REST API server
    """
    app = Flask("eho.api")

    # reading defaults
    app.config.from_pyfile("etc/default.cfg", silent=True)
    app.config.from_pyfile("../etc/default.cfg", silent=True)

    # read local conf
    app.config.from_pyfile("etc/local.cfg", silent=True)
    app.config.from_pyfile("../etc/local.cfg", silent=True)

    app.config.from_envvar("EHO_API_CFG", silent=True)
    app.config.update(**local_conf)

    root_logger = logging.getLogger()
    ll = app.config.pop("LOG_LEVEL", "WARN")
    if ll:
        root_logger.setLevel(ll)

    app.register_blueprint(api_v02.rest, url_prefix="/v0.2")

    if app.config["DEBUG"]:
        print "Configuration:"
        for k in app.config:
            print "\t%s = %s" % (k, app.config[k])

    setup_storage(app)
    setup_defaults(app)
    setup_scheduler(app)
    setup_ops(app)
    setup_api(app)

    def make_json_error(ex):
        status_code = ex.code if isinstance(ex, HTTPException) else 500
        description = ex.description if isinstance(ex, HTTPException) else str(ex)
        return render({"error": status_code, "error_message": description}, status=status_code)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    app.wsgi_app = auth_valid(app.config)(app.wsgi_app)

    app.wsgi_app = auth_token(
        app.config,
        auth_host=app.config["OS_AUTH_HOST"],
        auth_port=app.config["OS_AUTH_PORT"],
        auth_protocol=app.config["OS_AUTH_PROTOCOL"],
        admin_user=app.config["OS_ADMIN_USER"],
        admin_password=app.config["OS_ADMIN_PASSWORD"],
        admin_tenant=["OS_ADMIN_TENANT"],
    )(app.wsgi_app)

    return app
Beispiel #3
1
def create_app():
    """Create Flask app."""
    config = load_config()

    app = Flask(__name__)
    app.config.from_object(config)

    if not hasattr(app, "production"):
        app.production = not app.debug and not app.testing

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    if app.debug or app.testing:
        DebugToolbarExtension(app)

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {"/pages": os.path.join(app.config.get("PROJECT_PATH"), "application/pages")}
        )
    else:
        # Log errors to stderr in production mode
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        # Enable Sentry
        if app.config.get("SENTRY_DSN"):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get("SENTRY_DSN"))

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {
                "/static": os.path.join(app.config.get("PROJECT_PATH"), "output/static"),
                "/pkg": os.path.join(app.config.get("PROJECT_PATH"), "output/pkg"),
                "/pages": os.path.join(app.config.get("PROJECT_PATH"), "output/pages"),
            },
        )

    # Register components
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_hooks(app)

    return app
Beispiel #4
1
def create_app():
    """Create Flask app."""
    config = load_config()

    if config.DEBUG or config.TESTING:
        app = Flask(__name__)
    else:
        app = Flask(__name__, template_folder=os.path.join(project_path, "output/templates"))

    app.config.from_object(config)

    if not hasattr(app, "production"):
        app.production = not app.debug and not app.testing

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    # Log errors to stderr in production mode
    if app.production:
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        # Enable Sentry
        if app.config.get("SENTRY_DSN"):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get("SENTRY_DSN"))

        # Serve static files during production
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": os.path.join(project_path, "output")})
    else:
        DebugToolbarExtension(app)

        # Serve static files during development
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {"/uploads": os.path.join(app.config.get("PROJECT_PATH"), "uploads")}
        )

    # Register components
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_uploadsets(app)
    register_hooks(app)

    return app
Beispiel #5
1
def create_app():
    app = Flask(__name__)
    config = load_config()
    app.config.from_object(config)

    # CSRF protect
    csrf.init_app(app)

    if app.debug or app.testing:
        DebugToolbarExtension(app)

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {"/pages": os.path.join(app.config.get("PROJECT_PATH"), "application/pages")}
        )
    else:
        # Log errors to stderr in production mode
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        if app.config.get("SENTRY_DSN"):
            from application.utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get("SENTRY_DSN"))

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {
                "/static": os.path.join(app.config.get("PROJECT_PATH"), "output/static"),
                "/pkg": os.path.join(app.config.get("PROJECT_PATH"), "output/pkg"),
                "/pages": os.path.join(app.config.get("PROJECT_PATH"), "output/pages"),
            },
        )

    from application.utils.mails import mail

    mail.init_app(app)

    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_logger(app)
    register_uploadsets(app)
    register_hooks(app)

    return app
Beispiel #6
1
def create_app():
    app = Flask(__name__)
    app.wsgi_app = ReverseProxied(app.wsgi_app)
    configure_app(app)
    setup_error_email(app)
    login_manager.setup_app(app)
    return app
Beispiel #7
1
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_POST_LOGIN_VIEW"] = "/profile"
    app.config.from_object(Config)

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        twitter = current_app.social.twitter
        twitter.get_api()

        return render_template(
            "profile.html",
            content="Profile Page",
            twitter_conn=twitter.get_connection(),
            google_conn=current_app.social.google.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
            foursquare_conn=current_app.social.foursquare.get_connection(),
        )

    return app
Beispiel #8
1
def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Tcc3Portal platform.

    :param package_name: application package name.
    :param package_path: application package path.
    :param settings_override: a dictionary of settings to override.
    :param register_security_blueprint: flag to specify if the Flask-Security
                                        Blueprint should be registered. Defaults
                                        to `True`.
    :return: Flask application instance.
    """
    app = Flask(package_name, instance_relative_config=True)

    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3portal.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    # something need init
    # security.init_app(app, None, register_blueprint=register_security_blueprint)
    db.init_app(app)
    bootstrap.init_app(app)
    lm.init_app(app)
    babel.init_app(app)
    sso_client.init_app(app, lm)
    TccFrontend(app)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #9
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(_config)

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.realpath(config))

    if app.config["DEBUG"]:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

    api.init_app(app)
    babel.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    redis_store.init_app(app)
    CsrfProtect(app)

    register_auth(app)
    register_hooks(app)
    register_static(app)
    register_blueprints(app)
    configure_error_handles(app)
    plug_to_db(db)

    return app
def create_app():
    app = Flask(__name__, static_folder=os.path.join(PROJECT_ROOT, "public"), static_url_path="/public")

    app.config.update(os.environ)

    # TODO: read in right hand side from HT config vars
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_PASSWORD_HASH"] = "bcrypt"
    app.config["MONGODB_DB"] = "flask_security_test"
    app.config["MONGODB_HOST"] = "localhost"
    app.config["MONGODB_PORT"] = 27017

    app.debug = app.config["X_HT_DEBUG"] == "True"

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": os.path.join(os.path.dirname(__file__), "public")})

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("404.html"), 404

    SecuritySetup(app)

    # import & register blueprints here:
    # ===================================
    from hero_tmpl.views.security import security

    app.register_blueprint(security)

    from hero_tmpl.views.misc import misc

    app.register_blueprint(misc)

    return app
Beispiel #11
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("setting.py")
    register_blueprint(app)
    config_logging(app)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    return app
def create_app(config={}):
    app = Flask("chassis")
    app.config.from_envvar("FLASK_CONFIG")
    app.config.update(config)

    # External
    sentry.init_app(app)
    api.init_app(app)
    cache.init_app(app)

    # Internal
    db.init_app(app)

    # API Endpoints
    api.add_resource(CatAPI, "/cats/<int:cat_id>")

    with app.app_context():
        db.create_all()

    # Debug tools
    if app.debug:
        DebugToolbarExtension(app)
        if app.config.get("PROFILE", False):
            app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30], sort_by=("time", "cumulative"))

    return app
Beispiel #13
0
def create_app(config=None):
    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    config = config or os.environ.get("OPENEDX_WEBHOOKS_CONFIG") or "default"
    app.config.from_object(expand_config(config))

    sentry.init_app(app)
    db.init_app(app)
    create_celery_app(app)
    if not app.debug:
        SSLify(app)

    # attach Flask-Dance blueprints
    from .oauth import jira_bp as jira_oauth_bp

    app.register_blueprint(jira_oauth_bp, url_prefix="/login")
    from .oauth import github_bp as github_oauth_bp

    app.register_blueprint(github_oauth_bp, url_prefix="/login")

    # attach our blueprints
    from .github_views import github_bp

    app.register_blueprint(github_bp, url_prefix="/github")
    from .jira_views import jira_bp

    app.register_blueprint(jira_bp, url_prefix="/jira")
    from .ui import ui as ui_blueprint

    app.register_blueprint(ui_blueprint)
    from .tasks import tasks as tasks_blueprint

    app.register_blueprint(tasks_blueprint, url_prefix="/tasks")

    return app
Beispiel #14
0
def create_app(package_name, package_path, settings_override=None):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Overholt platform.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    :param register_security_blueprint: flag to specify if the Flask-Security
                                        Blueprint should be registered. Defaults
                                        to `True`.
    """
    app = Flask(package_name, instance_relative_config=True, instance_path=os.path.dirname(__file__))

    # app.config.from_object('vilya.settings')
    app.config.from_pyfile("settings.py")
    app.config.from_pyfile("settings-dev.py", silent=True)
    app.config.from_object(settings_override)

    db.init_app(app)
    cache.init_app(app)
    gitmodels.init_app(app)
    auth.init_app(app, db)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #15
0
def init_app(config="settings_prod.py"):

    app = Flask(__name__)

    configure_app(app, config)
    configure_before_handlers(app)
    configure_error_handlers(app)
    configure_extensions(app)
    configure_routes(app)

    if not app.debug:
        app.logger.info("Applying proxy fix.")

        from werkzeug.contrib.fixers import ProxyFix

        app.wsgi_app = ProxyFix(app.wsgi_app)

    # if app.debug:

    #    from pprint import pprint
    #    confstr = ""
    #    for key, val in app.config.iteritems():
    #        confstr += "  %s: %s\n" % (key, val)
    #    app.logger.info(confstr)

    return app
Beispiel #16
0
def create_app(config=None, app_name=None, blueprints=None):
    """Create a Flask app."""

    if app_name is None:
        app_name = DefaultConfig.PROJECT
    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    app = Flask(app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True)
    app.wsgi_app = ReverseProxied(app.wsgi_app)

    configure_app(app, config)
    configure_hook(app)
    configure_blueprints(app, blueprints)
    configure_extensions(app)
    configure_logging(app)
    configure_template_filters(app)
    configure_error_handlers(app)

    appsocket = create_decoder_socket(app)
    decoder = Decoder(app, appsocket)
    manager = Manager(app)
    app.decoder = decoder

    return app, appsocket
Beispiel #17
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Apply the SchemeProxyFix middleware
    app.wsgi_app = SchemeProxyFix(app.wsgi_app)

    # Add our cache
    if config_name == "production":  # pragma: no cover
        app.cache = FileSystemCache("recent_calls")
    else:
        app.cache = SimpleCache()

    bootstrap.init_app(app)
    db.init_app(app)

    from .setup import setup as setup_blueprint

    app.register_blueprint(setup_blueprint)

    from .voice import voice as voice_blueprint

    app.register_blueprint(voice_blueprint)

    # Register our custom template filter
    app.jinja_env.filters["national_format"] = convert_to_national_format

    return app
Beispiel #18
0
def create_app():
    app = Flask(__name__)

    # this could be cleaner
    if os.environ.get("HEROKU"):
        app.config.from_object(HerokuConfig)
    else:
        app.config.from_pyfile("../config.py")

    app.wsgi_app = ProxyFix(app.wsgi_app)

    api_bp = Blueprint("api", __name__)
    api = Api(api_bp)

    api.add_resource(RootAPI, "/analytics/api/v1.0")
    api.add_resource(CatalogListAPI, "/analytics/api/v1.0/catalogs/")
    api.add_resource(CatalogAPI, "/analytics/api/v1.0/catalogs/<catalog_name>")
    api.add_resource(ConditionListAPI, "/analytics/api/v1.0/conditions/")
    api.add_resource(EntryListAPI, "/analytics/api/v1.0/entries/")
    api.add_resource(EntryAPI, "/analytics/api/v1.0/entries/<entry_id>")
    api.add_resource(SymptomListAPI, "/analytics/api/v1.0/symptoms/")
    api.add_resource(TagAPI, "/analytics/api/v1.0/tags/<tag_name>")
    api.add_resource(TagListAPI, "/analytics/api/v1.0/tags/")
    api.add_resource(TreatmentListAPI, "/analytics/api/v1.0/treatments/")
    api.add_resource(TreatmentAPI, "/analytics/api/v1.0/treatments/<treatment_name>")
    api.add_resource(UserAPI, "/analytics/api/v1.0/users/<user_id>")
    api.add_resource(SegmentAPI, "/analytics/api/v1.0/segments")

    app.register_blueprint(api_bp)

    mongo.init_app(app)

    return app
Beispiel #19
0
def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Overholt platform.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    :param register_security_blueprint: flag to specify if the Flask-Security
                                        Blueprint should be registered. Defaults
                                        to `True`.
    """
    app = Flask(package_name, instance_relative_config=True)

    app.config.from_object("overholt.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    db.init_app(app)
    mail.init_app(app)
    security.init_app(app, SQLAlchemyUserDatastore(db, User, Role), register_blueprint=register_security_blueprint)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #20
0
def create_app(**kwargs):
    """Return the OAR API application instance."""
    app = Flask(__name__)
    app.wsgi_app = WSGIProxyFix(app.wsgi_app)
    app.wsgi_app = PrefixMiddleware(app.wsgi_app)
    config.setdefault_config(default_config)
    app.config.update(config)
    db.query_class = APIQuery
    db.query_collection_class = APIQueryCollection
    register_error_handlers(app)
    register_hooks(app)
    register_extensions(app)
    register_blueprints(app)
    register_proxy(app, **kwargs)

    return app
Beispiel #21
0
def create_app(**config):
    app = Flask(__name__)

    # Default config
    app.config.update(
        DEBUG=os.environ["DEBUG"],
        SECRET_KEY=os.environ["SECRET_KEY"],
        SQLALCHEMY_DATABASE_URI="postgresql://root:{}@db/{}".format(
            os.environ["MYSQL_ROOT_PASSWORD"], os.environ["MYSQL_DATABASE"]
        ),
        CSRF_ENABLED=True,
    )

    # Passed in config
    app.config.update(**config)

    # Extensions
    ext.db.init_app(app)
    ext.login_manager.init_app(app)

    # Views
    app.register_blueprint(views.pages)

    # API
    api.init_app(app)
    api.app = app

    # SASS
    if app.debug:
        app.wsgi_app = SassMiddleware(
            app.wsgi_app, dict({{cookiecutter.app_name}}=("static/sass", "static/css", "/static/css"))
        )

    return app
Beispiel #22
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    moment.init_app(app)
    toolbar.init_app(app)

    csrf.init_app(app)
    pages.init_app(app)
    freezer.init_app(app)

    from main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from blog import blog as blog_blueprint

    app.register_blueprint(blog_blueprint, url_prefix="/blog")

    app.wsgi_app = ProxyFix(app.wsgi_app)

    app.jinja_env.filters["htmltruncate"] = htmltruncate

    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler, SMTPHandler

        file_handler = RotatingFileHandler("tmp/healy.log", "a", 1 * 1024 * 1024, 10)
        file_handler.setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]")
        )
        app.logger.setLevel(logging.INFO)
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
        app.logger.info("healy startup")

        credentials = None
        secure = None

        if app.config["MAIL_USERNAME"] is not None:
            credentials = (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"])
            if app.config["MAIL_USE_TLS"] is True:
                secure = ()

        mail_handler = SMTPHandler(
            mailhost=(app.config["MAIL_SERVER"], app.config["MAIL_PORT"]),
            fromaddr=app.config["HEALY_MAIL_SENDER"],
            toaddrs=app.config["HEALY_ADMIN_EMAIL"],
            subject=app.config["HEALY_MAIL_SUBJECT_PREFIX"] + " Application Error",
            credentials=credentials,
        )

        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

    return app
Beispiel #23
0
def create_instance():
    """
    Construct a new Flask instance and return it.
    """
    import os

    app = Flask(__name__)
    app.config.from_object("notifico.default_config")

    if app.config.get("HANDLE_STATIC"):
        # We should handle routing for static assets ourself (handy for
        # small and quick deployments).
        import os.path
        from werkzeug import SharedDataMiddleware

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": os.path.join(os.path.dirname(__file__), "static")})

    if not app.debug:
        # If sentry (http://getsentry.com) is configured for
        # error collection we should use it.
        if app.config.get("SENTRY_DSN"):
            sentry.dsn = app.config.get("SENTRY_DSN")
            sentry.init_app(app)

    # Setup our redis connection (which is already thread safe)
    app.redis = Redis(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"], db=app.config["REDIS_DB"])
    cache.init_app(
        app, config={"CACHE_TYPE": "redis", "CACHE_REDIS_HOST": app.redis, "CACHE_OPTIONS": {"key_prefix": "cache_"}}
    )
    db.init_app(app)

    with app.app_context():
        # Let SQLAlchemy create any missing tables.
        db.create_all()

    # Import and register all of our blueprints.
    from notifico.views.account import account
    from notifico.views.public import public
    from notifico.views.projects import projects
    from notifico.views.pimport import pimport
    from notifico.views.admin import admin

    app.register_blueprint(account, url_prefix="/u")
    app.register_blueprint(projects)
    app.register_blueprint(public)
    app.register_blueprint(pimport, url_prefix="/i")
    app.register_blueprint(admin, url_prefix="/_")

    # cia.vc XML-RPC kludge.
    from notifico.services.hooks.cia import handler

    handler.connect(app, "/RPC2")

    # Setup some custom Jinja2 filters.
    app.jinja_env.filters["pretty_date"] = pretty.pretty_date
    app.jinja_env.filters["plural"] = pretty.plural
    app.jinja_env.filters["fix_link"] = pretty.fix_link

    return app
def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the application.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    :param register_security_blueprint: flag to specify if the Flask-Security
    Blueprint should be registered. Defaults
    to `True`.
    """
    app = Flask(package_name, instance_relative_config=True)

    app.config.from_object("project.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    db.init_app(app)
    mail.init_app(app)
    jwt.init_app(app)
    bouncer.init_app(app)

    @jwt.authentication_handler
    def authenticate(username, password):
        account = accounts.first(email=username)
        if not account:
            return None

        if not check_password(password, account.password):
            return None

        return account

    @jwt.user_handler
    def load_user(payload):
        return accounts.get(payload["account_id"])

    @jwt.payload_handler
    def make_payload(account):
        exp = datetime.datetime.utcnow() + app.config["JWT_EXPIRATION_DELTA"]
        return {"account_id": account.id, "exp": exp.strftime(app.config["JSON_DATETIME_FORMAT"])}

    @bouncer.authorization_method
    def define_authorization(user, they):
        if user.is_admin:
            they.can(MANAGE, ALL)
        else:
            they.can(READ, "Account")
            they.can(EDIT, "Account", lambda a: a.id == user.id)

    @bouncer.user_loader
    def get_current_user():
        return current_user

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #25
0
def create_app(name=None, config=None):
    """Create the Flask application."""
    name = "kwalitee" if name is None else name
    app = Flask(
        name,
        template_folder="templates",
        static_folder="static",
        instance_relative_config=True,
        instance_path=os.environ.get("KWALITEE_INSTANCE_PATH"),
    )

    # Load default configuration
    app.config.from_object("kwalitee.config")

    # Load kwalitee.cfg from instance folder
    app.config.from_pyfile("kwalitee.cfg", silent=True)
    app.config.from_envvar("KWALITEE_CONFIG", silent=True)
    app.config.update(config or {})

    # Create instance path
    if not os.path.exists(app.instance_path):
        os.makedirs(app.instance_path)

    # Setting up the database
    from . import models

    models.init_app(app)

    # Setting up RQ
    from . import worker

    worker.init_app(app)

    # Setting up the views
    app.url_map.converters["sha"] = ShaConverter
    from . import views

    app.add_url_rule("/", "index", views.index, methods=["GET"])
    app.add_url_rule("/<account>/", "account", views.account, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/", "repository", views.repository, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/commits/<sha:sha>/", "commit", views.commit, methods=["GET"])
    app.add_url_rule(
        "/<account>/<repository>/branches/<sha:sha>/<path:branch>",
        "branch_status",
        views.branch_status,
        methods=["GET"],
    )
    app.add_url_rule("/<account>/<repository>/branches/<path:branch>", "branch", views.branch, methods=["GET"])
    app.add_url_rule("/payload", "payload", views.payload, methods=["POST"])
    # legacy
    app.add_url_rule("/status/<sha>", "status", views.status, methods=["GET"])

    if app.debug:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)

    return app
Beispiel #26
0
def create_app(config_or_path="../redwind.cfg"):
    from redwind import extensions
    from redwind.views import views
    from redwind.admin import admin
    from redwind.services import services
    from redwind.micropub import micropub
    from redwind.imageproxy import imageproxy

    app = Flask(__name__)
    if isinstance(config_or_path, dict):
        app.config.update(config_or_path)
    else:
        app.config.from_pyfile(config_or_path)

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True
    app.jinja_env.add_extension("jinja2.ext.autoescape")
    app.jinja_env.add_extension("jinja2.ext.with_")
    app.jinja_env.add_extension("jinja2.ext.i18n")

    extensions.init_app(app)

    if app.config.get("PROFILE"):
        from werkzeug.contrib.profiler import ProfilerMiddleware

        f = open("logs/profiler.log", "w")
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, f, restrictions=[60], sort_by=("cumtime", "tottime", "ncalls"))

    # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
    if not app.debug:
        app.logger.setLevel(logging.DEBUG)
        stream_handler = StreamHandler()
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        stream_handler.setFormatter(formatter)
        app.logger.addHandler(stream_handler)

        recipients = app.config.get("ADMIN_EMAILS")
        if recipients:
            error_handler = SMTPHandler("localhost", "Redwind <redwind@kylewm.com>", recipients, "redwind error")
            error_handler.setLevel(logging.ERROR)
            error_handler.setFormatter(Formatter(MAIL_FORMAT))
            app.logger.addHandler(error_handler)

    app.register_blueprint(views)
    app.register_blueprint(admin)
    app.register_blueprint(services)
    app.register_blueprint(micropub)
    app.register_blueprint(imageproxy)

    for plugin in ["facebook", "instagram", "locations", "push", "twitter", "wm_receiver", "wm_sender", "wordpress"]:
        # app.logger.info('loading plugin module %s', plugin)
        module = importlib.import_module("redwind.plugins." + plugin)
        try:
            module.register(app)
        except:
            app.logger.warn("no register method for plugin module %s", plugin)

    return app
Beispiel #27
0
def create_app():
    """创建Flask app"""
    app = Flask(__name__)

    config = load_config()
    app.config.from_object(config)

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    if app.debug:
        DebugToolbarExtension(app)

        # serve static files during development
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {"/uploads": os.path.join(app.config.get("PROJECT_PATH"), "uploads")}
        )
    else:
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        if app.config.get("SENTRY_DSN"):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get("SENTRY_DSN"))

    # 注册组件
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_uploadsets(app)

    # before every request
    @app.before_request
    def before_request():
        ban_ips = app.config.get("BAN_IPS")
        if request.remote_addr in ban_ips:
            abort(404)
        g.user = get_current_user()

    return app
Beispiel #28
0
def create_app(config="widukind_web.settings.Prod", db=None):

    env_config = config_from_env("WIDUKIND_SETTINGS", config)

    app = Flask(__name__)
    app.config.from_object(env_config)

    _conf_db(app, db=db)

    app.config["LOGGER_NAME"] = "widukind_web"
    app._logger = _conf_logging(debug=app.debug, prog_name="widukind_web")

    if app.config.get("LOGGING_MONGO_ENABLE", True):
        _conf_logging_mongo(app)

    if app.config.get("LOGGING_MAIL_ENABLE", False):
        _conf_logging_mail(app)

    _conf_logging_errors(app)

    extensions.moment.init_app(app)

    _conf_bootstrap(app)

    _conf_sentry(app)

    _conf_errors(app)

    _conf_cache(app)

    _conf_converters(app)

    _conf_jsonify(app)

    _conf_default_views(app)

    _conf_bp(app)

    _conf_record_query(app)

    _conf_processors(app)

    _conf_periods(app)

    _conf_auth(app)

    _conf_sitemap(app)

    _conf_session(app)

    _conf_mail(app)

    _conf_assets(app)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app
def app():
    test_app = Flask(__name__)
    test_app.wsgi_app = HTTPMethodOverrideMiddleware(test_app.wsgi_app)

    @test_app.route("/", methods=HTTPMethodOverrideMiddleware.allowed_methods)
    def index():
        return request.method

    return test_app
Beispiel #30
0
def create_app(config):
    app = Flask(__name__, static_url_path="")

    app.config.from_object(config)

    if app.config["ON_HEROKU"]:
        app.wsgi_app = ProxyFix(app.wsgi_app)
        SSLify(app, age=300, permanent=True)

    # Setup login manager
    login_manager.init_app(app)
    login_manager.login_view = "page.LoginView:index"
    login_manager.login_message = ""

    # Create instance of user
    from models.user import User

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

    # Make current logged in user accesible at g.user
    @app.before_request
    def before_request():
        g.user = current_user

    # Import blueprints from views modules
    from todowhat.views.page import page
    from todowhat.views.api import api
    from todowhat.views.error import error

    # Register blueprints
    app.register_blueprint(page)
    app.register_blueprint(api)
    app.register_blueprint(error)

    # Setup database
    db.init_app(app)

    # Setup email
    mail = Mail(app)
    app.wsgi_app = GzipMiddleware(app.wsgi_app, compresslevel=5)

    return app