Example #1
0
def create_app(redis_client=None, job_queue=None):
    config = get_config()

    app = Flask(__name__)
    CORS(app)

    # Maximum number of URLs to receive in an API call
    app.config.update(config)

    app.redis_client = redis_client or get_redis_client()

    app.job_queue = job_queue or get_job_queue(app.redis_client)

    app.embedly_client = get_embedly_client(app.redis_client, app.job_queue)

    app.mozilla_client = get_mozilla_client(app.redis_client, app.job_queue)

    app.pocket_client = get_pocket_client(app.redis_client, app.job_queue)

    app.config['VERSION_INFO'] = ''
    if os.path.exists('./version.json'):  # pragma: no cover
        with open('./version.json') as version_file:
            app.config['VERSION_INFO'] = version_file.read()

    app.register_blueprint(api.views.blueprint)

    app.sentry = Sentry(app)

    return app
Example #2
0
def create_app(config_obj: Config, no_sql: bool=False) -> Flask:

    """Create an application."""
    app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder=STATIC_FOLDER)
    config_dict = dict([(k, getattr(config_obj, k)) for k in dir(config_obj) if not k.startswith('_')])
    app.config.update(config_dict)

    # Import DB models. Flask-SQLAlchemy doesn't do this automatically like Celery does.
    with app.app_context():
        for model in app.config.get('DB_MODELS_IMPORTS', list()):
            import_module(model)

    for bp in all_blueprints:
        import_module(bp.import_name)
        app.register_blueprint(bp)

    class FloatJSONEncoder(flask.json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, decimal.Decimal):
                # Convert decimal instances to float.
                return float(obj)
            return super(FloatJSONEncoder, self).default(obj)

    app.json_encoder = FloatJSONEncoder

    def url_for_other_page(page: int):
        args = request.view_args.copy()
        args['page'] = page
        return url_for(request.endpoint, **args)

    app.jinja_env.globals['url_for_other_page'] = url_for_other_page

    if not no_sql:
        db.init_app(app)

    migrate.init_app(app, db)
    sentry.init_app(app)
    babel.init_app(app)
    navigation.init_app(app)
    celery.init_app(app)

    login_manager.init_app(app)
    login_manager.login_view = "sign.index.login"
    login_manager.login_message_category = "info"
    login_manager.localize_callback = gettext

    login_manager.refresh_view = "sign.index.login"
    login_manager.needs_refresh_message = (
        u"To protect your account, please reauthenticate to access this page."
    )
    login_manager.needs_refresh_message_category = "info"

    app.sentry = sentry

    with app.app_context():
        import_module('gitlab_tools.middleware')

    return app
Example #3
0
def create_app(name=None):
    app = Flask(name)

    if os.environ.get('PRODUCTION'):
        app.config.from_object(ProductionConfig)
        print "running with ProductionConfig"
    else:
        app.config.from_object(DefaultConfig)
        print "running with DefaultConfig"

    # sentry
    if app.config.get('SENTRY_DSN'):
        sentry = Sentry()
        sentry.init_app(app)
        app.sentry = sentry

    # assets
    assets = Environment(app)
    assets.url = app.static_url_path
    scss_bundle = Bundle('css/*.scss', 'css/*.css',
        filters=['scss', 'cssmin'], depends='css/*.scss', output='css/all.css')
    assets.register('scss_all', scss_bundle)
    js_bundle = Bundle('js/*.js', filters='rjsmin', output='js/all.js')
    assets.register('js_all', js_bundle)
    Compress(app)

    # cache
    if app.config['DEBUG']:
        cache_type = 'null'
    else:
        cache_type = 'simple'

    cache = Cache(config={'CACHE_TYPE': cache_type})
    cache.init_app(app)
    app.cache = cache

    # CDN
    cdn = CDN()
    cdn.init_app(app)

    # workaround flask-assets / flask-cdn integration
    if app.config.get('CDN_HTTPS'):
        cdn_scheme = 'https'
    else:
        cdn_scheme = 'http'
    if app.config.get('FLASK_ASSETS_USE_CDN') and app.config.get('CDN_DOMAIN'):
        app.jinja_env.globals['FLASK_CDN'] = '%s://%s' % (cdn_scheme, app.config['CDN_DOMAIN'])

    return app
Example #4
0
def create_app(config_file=None):
    app = Flask(__name__)
    app = change_jinja_templates(app)
    if config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("CLA_PUBLIC_CONFIG")

    if app.config.get("SENTRY_DSN"):
        app.sentry = Sentry(app,
                            dsn=app.config.get("SENTRY_DSN"),
                            logging=True,
                            level=logging.ERROR)

    app.babel = Babel(app)
    app.babel.localeselector(get_locale)

    app.cache = Cache(app)

    app.mail = Mail(app)

    for extension in app.config["EXTENSIONS"]:
        extension.init_app(app)

    app.session_interface = CheckerSessionInterface()
    app.json_encoder = CustomJSONEncoder

    register_error_handlers(app)

    app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name")

    app.register_blueprint(base)
    app.register_blueprint(geocoder)
    app.register_blueprint(contact)
    app.register_blueprint(scope)
    if not app.config.get("CONTACT_ONLY"):
        app.register_blueprint(checker)

    logging.config.dictConfig(app.config["LOGGING"])
    # quiet markdown module
    logging.getLogger("MARKDOWN").setLevel(logging.WARNING)

    if app.debug:
        from werkzeug.debug import DebuggedApplication

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

    return app
Example #5
0
def create_app(config_file=None):
    app = Flask(__name__)
    app = change_jinja_templates(app)
    if config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("CLA_PUBLIC_CONFIG")

    if app.config.get("SENTRY_DSN"):
        app.sentry = Sentry(app, dsn=app.config.get("SENTRY_DSN"), logging=True, level=logging.ERROR)

    app.babel = Babel(app)
    app.babel.localeselector(get_locale)

    app.cache = Cache(app)

    app.mail = Mail(app)

    for extension in app.config["EXTENSIONS"]:
        extension.init_app(app)

    app.session_interface = CheckerSessionInterface()
    app.json_encoder = CustomJSONEncoder

    register_error_handlers(app)

    app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name")

    app.register_blueprint(base)
    app.register_blueprint(geocoder)
    app.register_blueprint(contact)
    app.register_blueprint(scope)
    if not app.config.get("CONTACT_ONLY"):
        app.register_blueprint(checker)

    logging.config.dictConfig(app.config["LOGGING"])
    # quiet markdown module
    logging.getLogger("MARKDOWN").setLevel(logging.WARNING)

    if app.debug:
        from werkzeug.debug import DebuggedApplication

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

    return app
Example #6
0
File: app.py Project: insom/phoney
def create_app(conf_obj=Settings, conf_file='/etc/phoney.cfg',
               login_required=None):
    app = Flask(__name__)
    app.config.from_object(conf_obj)
    app.config.from_pyfile(conf_file, silent=True)

    if app.config['DB_SECRET_KEY'] == 'INSECURE_DEFAULT':
        if not (app.debug or app.testing):
            raise ValueError('Cannot use insecure key in PROD')

    db.init_app(app)
    register_blueprints(app)

    @app.route('/')
    def index():
        return redirect(url_for('numbers.index'))

    app.sentry = Sentry(app)

    return app
Example #7
0
def create_app(env):
    """
    We use an application factory to allow the app to be configured from the
    command line at start up.
    """

    # Create the app
    app = Flask(__name__)

    # Configure the application to the specified config
    app.config['ENV'] = env
    app.config.from_object('settings.{0}.Config'.format(env))

    # Add celery
    app.celery = create_celery_app(app)

    # Add sentry logging if the DSN is provided
    if app.config['SENTRY_DSN']:
        app.sentry = sentry.init_app(app)

    # Add mongo support
    app.mongo = pymongo.MongoClient(app.config['MONGO_URI'])
    app.db = app.mongo.get_default_database()
    Frame._client = app.mongo

    if app.config.get('MONGO_PASSWORD'):
        Frame.get_db().authenticate(app.config.get('MONGO_USERNAME'),
                                    app.config.get('MONGO_PASSWORD'))

    # Fix for REMOTE_ADDR value
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # Import views as a blueprint
    import api
    app.register_blueprint(api.api)
    return app
Example #8
0
File: app.py Project: nic0d/osmbot
import logging

from flask import Flask, request, current_app
from bot import Osmbot
from configobj import ConfigObj
import os
from raven.contrib.flask import Sentry
import telegram

application = Flask(__name__)
application.debug = True
Osmbot(application, '')

config = ConfigObj('bot.conf')
token = config['token']
telegram_api = telegram.Bot(config['token'])
if 'sentry_dsn' in config:
    application.config['sentry_dsn'] = config['sentry_dsn']
    sentry = Sentry(application, dsn=config['sentry_dsn'])
    sentry.captureMessage('OSMBot started', level=logging.INFO)
    application.sentry = sentry

webhook = os.path.join(config['webhook'], config['token'])
application.logger.debug('webhook:%s', config['webhook'])
result = telegram_api.setWebhook(webhook)
if result:
    application.logger.debug('Webhook set')

if __name__ == '__main__':
    application.run(host='0.0.0.0', debug=True)
Example #9
0
File: app.py Project: Xevib/osmbot
from flask import Flask, request, current_app
from bot import Osmbot
from configobj import ConfigObj
import os
from raven.contrib.flask import Sentry
import telegram

application = Flask(__name__)
application.debug = True
Osmbot(application, '')

config = ConfigObj('bot.conf')
token = config['token']
telegram_api = telegram.Bot(config['token'])
if 'sentry_dsn' in config:
    application.config['sentry_dsn'] = config['sentry_dsn']
    sentry = Sentry(application, dsn=config['sentry_dsn'])
    sentry.captureMessage('OSMBot started', level=logging.INFO)
    application.sentry = sentry

webhook = os.path.join(config['webhook'], config['token'])
application.logger.debug('webhook:%s', config['webhook'])
result = telegram_api.setWebhook(webhook)
if result:
    application.logger.debug('Webhook set')


if __name__ == '__main__':
    application.run(host='0.0.0.0', debug=True)