Beispiel #1
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 #2
0
def create_app(config):
    app = Flask(__name__)
    config = os.path.abspath(config)
    app.config.from_pyfile(config)
    app.debug = app.config.get('DEBUG', False)

    # Setup semi-permanent cache stored in os temp directory
    try:
        app.cache_file = os.path.join(tempfile.gettempdir(),
                                      'spectrometer-cache.p')
        app.cache = pickle.load(open(app.cache_file, "rb"))
    except IOError:
        app.cache = {}

    # Flask profiler is only active when in debug mode
    profiler = Profiler()
    profiler.init_app(app)

    if not app.debug:
        # Setup Logger
        logdir = app.config.get('LOG_DIR', '/var/log/spectrometer')
        logfile = os.path.join(logdir, 'spectrometer.log')

        logging.getLogger().setLevel(logging.NOTSET)
        logging.getLogger('git.cmd').setLevel(logging.INFO)
        formatter = logging.Formatter(
            '%(asctime)s (%(levelname)8s) %(name)-40s: %(message)s')
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logging.getLogger().addHandler(console_handler)

        try:
            file_handler = RotatingFileHandler(logfile,
                                               maxBytes=20000000,
                                               backupCount=20)
            file_handler.setFormatter(formatter)
            logging.getLogger().addHandler(file_handler)
            log.info('File logger activated.')
        except IOError:
            log.warn(
                'Unable to activate File logger. Please ensure that the '
                'log directory ({0}) is writable by the spectrometer user.'.
                format(logdir))

    # Prep resource handlers
    app.gerrithandler = GerritHandler(app.config['GERRIT_URL'])
    app.githandlers = {}

    # Stop Flask debug mode from running the scheduler twice
    if not app.debug or os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        run_scheduler(app)

    app.route('/')(views.status)

    app.register_blueprint(gitapi, url_prefix='/git')
    app.register_blueprint(gerritapi, url_prefix='/gerrit')

    return app
Beispiel #3
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)
    app.debug = app.config.get('DEBUG', False)

    # Setup semi-permanent cache stored in os temp directory
    try:
        app.cache_file = os.path.join(
            tempfile.gettempdir(), 'spectrometer-cache.p')
        app.cache = pickle.load(open(app.cache_file, "rb"))
    except IOError:
        app.cache = {}

    # Flask profiler is only active when in debug mode
    profiler = Profiler()
    profiler.init_app(app)

    if not app.debug:
        # Setup Logger
        logdir = app.config.get('LOG_DIR', '/var/log/spectrometer')
        logfile = os.path.join(logdir, 'spectrometer.log')

        logging.getLogger().setLevel(logging.NOTSET)
        formatter = logging.Formatter('%(asctime)s (%(levelname)8s) %(name)-40s: %(message)s')
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logging.getLogger().addHandler(console_handler)

        try:
            file_handler = RotatingFileHandler(logfile, maxBytes=20000000, backupCount=20)
            file_handler.setFormatter(formatter)
            logging.getLogger().addHandler(file_handler)
            log.info('File logger activated.')
        except IOError:
            log.warn('Unable to activate File logger. Please ensure that the '
                     'log directory ({0}) is writable by the spectrometer user.'.format(logdir))

    # Prep resource handlers
    app.gerrithandler = GerritHandler(app.config['GERRIT_URL'])
    app.githandlers = {}

    # Stop Flask debug mode from running the scheduler twice
    if not app.debug or os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        run_scheduler(app)

    app.route('/')(views.status)

    app.register_blueprint(gitapi, url_prefix='/git')
    app.register_blueprint(gerritapi, url_prefix='/gerrit')

    return app
Beispiel #4
0
def make_app(cache=None, config=None):

    if config is None:
        config = Config()

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

    if cache is None:
        cache = Cache(config=config)

    app.cache = cache

    # Get the fallback server from shotgun_api3_registry.
    passthrough_server = app.config.setdefault(
        'PASSTHROUGH_SERVER',
        get_shotgun_kwargs(config)['base_url'].strip('/'))
    app.config.setdefault('PASSTHROUGH_URL', passthrough_server + '/api3/json')

    # We use one HTTP session for everything.
    app.http_session = requests.Session()

    # Register the logic.
    app.register_blueprint(blueprint)

    return app
Beispiel #5
0
def create_app(config='CTFd.config'):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        app.jinja_loader = ThemeLoader(os.path.join(app.root_path,
                                                    app.template_folder),
                                       followlinks=True)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
        if url.drivername == 'postgres':
            url.drivername = 'postgresql'

        db.init_app(app)

        try:
            if not (url.drivername.startswith('sqlite')
                    or database_exists(url)):
                create_database(url)
            db.create_all()
        except OperationalError:
            db.create_all()
        except ProgrammingError:  ## Database already exists
            pass
        else:
            db.create_all()

        app.db = db

        cache.init_app(app)
        app.cache = cache

        if not get_config('ctf_theme'):
            set_config('ctf_theme', 'original')

        #Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        from CTFd.plugins import init_plugins

        init_plugins(app)

        return app
Beispiel #6
0
    def _make_app():
        global CELERY_FLASK_APP

        if CELERY_FLASK_APP:
            return CELERY_FLASK_APP

        from app import init_blueprints, init_services
        app = Flask(__name__)
        if not isinstance(config, dict):
            app.config.update(config.settings)
        else:
            app.config.update(config)

        app.validator_context = ValidatorContext()
        app.rendering_context = RenderingContext()
        app.model_cache_context = ModelCacheContext()
        app.external_tools = external_tools
        load_filters(app.jinja_env, app.config)
        set_template_loader(app.jinja_env)
        init_blueprints(app)
        init_services(app)
        if not app.config['TEST']:
            init_sql_db(app)
        app.cache = external_tools.cache
        app.logger_name = "celery"
        # log_file_path = os.path.join(os.path.split(app.config['log_file_path'])[0], "celeryd.log")
        # file_handler = TimedRotatingFileHandler(log_file_path, backupCount=7, encoding='utf-8', when="midnight")
        # file_handler.setLevel()
        # file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        app.logger.setLevel(app.config['CELERY_LOG_LEVEL'])

        CELERY_FLASK_APP = app
        return app
Beispiel #7
0
def create_app(settings_override=None):
    """
    Create a Flask application using the app factory pattern.
    :param settings_override: Override settings
    :return: Flask app
    """
    app = Flask(__name__, instance_relative_config=True)

    def disable_varnish(response):
        response.cache_control.private = True
        return response

    app.after_request(disable_varnish)

    SSLify(app, skips=['healthcheck'])
    gunicorn_logger = logging.getLogger('gunicorn.error')
    app.logger.handlers = gunicorn_logger.handlers
    app.logger.setLevel(gunicorn_logger.level)

    app.config.from_object('config.settings')

    if 'GOOGLE_CLIENT_ID' in app.config:
        setup_authentication(app)

    app.register_blueprint(page)

    plugins = {}
    for plugin in app.config['ENABLED_PLUGINS']:
        module = importlib.import_module(f'dashboard.plugins.{plugin}')
        app.register_blueprint(module.plugin, url_prefix=module.base_path)
        plugins[plugin] = {'tab_name': module.tab_name}

    app.airflow_data_provider = AirflowDBDataProvider(
        app.config, app.logger, MySQLClient(app.config, app.logger))
    app.influx_data_provider = InfluxDBData(
        app.config, app.logger) if app.config.get('INFLUXDB_HOST') else None
    app.prometheus_data_provider = PrometheusData(
        app.config, app.logger) if app.config.get('PROMETHEUS_HOST') else None

    # Reading tables configs, setting variable to `None` if file is not present
    tables = get_yaml_file_content(TABLES_PATH)

    app.table_data_provider = TableDataProvider(
        app.airflow_data_provider, app.influx_data_provider,
        app.prometheus_data_provider, tables, app.logger,
        app.config) if tables else None

    app.etl_data_provider = EtlDataProvider(app.config,
                                            app.airflow_data_provider,
                                            app.table_data_provider)

    app.async_request_executor = ThreadPoolExecutor(max_workers=3)
    app.cache = SimpleCache()

    if app.debug:
        app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)

    app.context_processor(lambda: {'now': datetime.now(), 'plugins': plugins})

    return app
Beispiel #8
0
def create_app(testing_config=None):
    # create base Flask app and configure based on environment
    app = Flask(__name__)
    if not testing_config:
        app.config.from_pyfile("settings.py")
    else:
        app.config.from_mapping(testing_config)

    # setup db and migrations
    setup_db(app)
    Migrate(app, app.config["db"])

    # Add flask-restful API resources
    api = Api(app)
    api.add_resource(BooksView, "/api/books")
    api.add_resource(BookView, "/api/books/<int:book_id>")
    api.add_resource(SubseriesListView, "/api/subseries")
    api.add_resource(SubseriesView, "/api/subseries/<int:subseries_id>")

    # add rate limiter to entire application
    Limiter(app, key_func=gra, default_limits="200/day 50/hour".split())

    # add cache
    cache.init_app(app)
    app.cache = cache

    # add non-API endpoints
    add_login_flow_routes(app)
    register_error_handlers(app)

    return app
Beispiel #9
0
def create_app():
    """
    Create the application and return it to the user
    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    Consul(app)

    load_config(app)

    logging.config.dictConfig(
        app.config['OBJECTS_LOGGING']
    )

    app.cache = Cache(app) 

    api = Api(app)
    api.add_resource(ObjectSearch, '/', '/<string:objects>', '/<string:objects>/<string:source>')
    api.add_resource(PositionSearch, '/pos/<string:pstring>')
    api.add_resource(QuerySearch, '/query')

    discoverer = Discoverer(app)

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

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar('XSNIPPET_WEBUI_SETTINGS', silent=True)

    # set jinja2 global vars to be used in all templates
    app.jinja_env.globals.update(
        {
            "title": app.config["TITLE"],
            "abs_url_for": abs_url_for,
            "lang_by_short_name": lang_by_short_name
        }
    )
    # set assets env
    assets.Environment(app)

    app.register_blueprint(webui)

    # register all needed hooks
    app.before_request(create_http_object)

    # create cache connection (it's thread-safe)
    app.cache = create_cache_connection(app, key_prefix="webui_")

    return app
def create_app():
    application = Flask(__name__)

    init_app(application)

    load_config(application)

    from app.precompiled import precompiled_blueprint
    from app.preview import preview_blueprint
    from app.status import status_blueprint
    application.register_blueprint(status_blueprint)
    application.register_blueprint(preview_blueprint)
    application.register_blueprint(precompiled_blueprint)

    application.statsd_client = StatsdClient()
    application.statsd_client.init_app(application)
    application.encryption_client = Encryption()
    application.encryption_client.init_app(application)
    utils_logging.init_app(application, application.statsd_client)
    weasyprint_hack.init_app(application)
    request_helper.init_app(application)
    notify_celery.init_app(application)

    application.cache = init_cache(application)

    @auth.verify_token
    def verify_token(token):
        return token in application.config['TEMPLATE_PREVIEW_INTERNAL_SECRETS']

    return application
Beispiel #12
0
def create_app():
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object('config.Config')

    db.init_app(app)
    cache.init_app(app)

    with app.app_context():
        from api.routes.cache import cache_bp
        from api.routes.login import login_bp
        from api.routes.person import person_bp
        from api.routes.errors import errors_bp

        db.create_all()

        app.register_blueprint(cache_bp, url_prefix='/cache')
        app.register_blueprint(login_bp, url_prefix='/login')
        app.register_blueprint(person_bp, url_prefix='/person')
        app.register_blueprint(errors_bp)

        app.cache = Cache(app)

        formatter = logging.Formatter(
            "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"
        )
        handler = RotatingFileHandler(f'logs/{date.today()}.log',
                                      maxBytes=10000,
                                      backupCount=1)
        handler.setLevel(logging.DEBUG)
        handler.setFormatter(formatter)
        app.logger.addHandler(handler)
        app.logger.setLevel(logging.DEBUG)

        return app
Beispiel #13
0
def create_app(config=None, environment=None, debug=False):
    app = Flask(__name__)
    app.config['ENVIRONMENT'] = environment
    app.config.update(config or {})
    app.debug = debug

    app.api = Api(app,
                  prefix='/api/v1',
                  errors=api_error_map,
                  catch_all_404s=True)

    app.cache = Cache(app, config=APP_CONFIG['flask_cache_config'])

    app.stats_redis = Redis(host=REDIS_CONFIG['redis_host'],
                            port=REDIS_CONFIG['redis_port'],
                            password=REDIS_CONFIG['redis_pass'],
                            db=1)
    setup_logging(app)
    app.nextbus_api = NextbusApiClient(agency='sf-muni')
    from nextbus.router import setup_router
    setup_router(app)

    from nextbus.common.nextbusapi import NextbusObjectSerializer
    app.config.update({
        'RESTFUL_JSON': {
            'separators': (', ', ': '),
            'indent': 2,
            'cls': NextbusObjectSerializer
        }
    })
    from nextbus.resources import teardown_request
    app.teardown_request(teardown_request)
    setup_errorhandlers(app)

    return app
Beispiel #14
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 CBP Admin 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)

    config_name = os.getenv('FLASK_CONFIG') or 'default'
    app.config.from_object(config[config_name])
    app.config.from_pyfile('settings.cfg', silent=True)
    app.config.from_object(settings_override)
    # locale.setlocale(locale.LC_ALL, app.config['LOCALE'])

    app.cache = cache
    es.init_app(app)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

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

    app.cache = Cache(app, config={
        'CACHE_TYPE': CACHE_TYPE,
        'CACHE_REDIS_HOST': REDIS_HOST,
        'CACHE_REDIS_PORT': REDIS_PORT,
        'CACHE_REDIS_DB': REDIS_DB
    })
    app.cache.init_app(app)

    app.logger.info(f'Creating application on port {APPLICATION_PORT}...')

    app.port = APPLICATION_PORT
    app.host = APPLICATION_HOST

    app.logger.info(
        f'Initializing Mongo host: {MONGO_HOST}, port: {MONGO_PORT}, user: {MONGO_USERNAME}, pass: {MONGO_PASSWORD}, database: {MONGO_DATABASE}')
    from pymongo import MongoClient
    client = MongoClient(host=MONGO_HOST,
                         port=MONGO_PORT,
                         username=MONGO_USERNAME,
                         password=MONGO_PASSWORD)
    from app.database import Todos
    app.todos = Todos(database=MONGO_DATABASE, collection=MONGO_TODOS_COLLECTION_NAME, mongo_client=client)
    app.logger.info(f'Initializing todos repo {app.todos}...')

    from app.route import routes
    app.logger.info('Initializing routes...')
    app.register_blueprint(routes, url_prefix='/api')

    return app
Beispiel #16
0
def create_application(config=None):
    global app

    # Flask!
    app = Flask(__name__)
    app.config.from_object('supysonic.config.DefaultConfig')

    if not config:  # pragma: nocover
        config = IniConfig.from_common_locations()
    app.config.from_object(config)

    # Set loglevel
    logfile = app.config['WEBAPP']['log_file']
    if logfile:  # pragma: nocover
        from logging.handlers import TimedRotatingFileHandler
        handler = TimedRotatingFileHandler(logfile, when='midnight')
        handler.setFormatter(
            logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
        logger.addHandler(handler)
    loglevel = app.config['WEBAPP']['log_level']
    if loglevel:
        logger.setLevel(getattr(logging, loglevel.upper(), logging.NOTSET))

    # Initialize database
    init_database(app.config['BASE']['database_uri'])
    app.wsgi_app = db_session(app.wsgi_app)

    # Insert unknown mimetypes
    for k, v in app.config['MIMETYPES'].items():
        extension = '.' + k.lower()
        if extension not in mimetypes.types_map:
            mimetypes.add_type(v, extension, False)

    # Initialize Cache objects
    # Max size is MB in the config file but Cache expects bytes
    cache_dir = app.config['WEBAPP']['cache_dir']
    max_size_cache = app.config['WEBAPP']['cache_size'] * 1024**2
    max_size_transcodes = app.config['WEBAPP']['transcode_cache_size'] * 1024**2
    app.cache = Cache(path.join(cache_dir, "cache"), max_size_cache)
    app.transcode_cache = Cache(path.join(cache_dir, "transcodes"),
                                max_size_transcodes)

    # Test for the cache directory
    cache_path = app.config['WEBAPP']['cache_dir']
    if not path.exists(cache_path):
        makedirs(cache_path)  # pragma: nocover

    # Read or create secret key
    app.secret_key = get_secret_key('cookies_secret')

    # Import app sections
    if app.config['WEBAPP']['mount_webui']:
        from .frontend import frontend
        app.register_blueprint(frontend)
    if app.config['WEBAPP']['mount_api']:
        from .api import api
        app.register_blueprint(api, url_prefix='/rest')

    return app
Beispiel #17
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    CORS(app)
    cache.init_app(app, config=app.config)
    app.cache = cache

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .mauticor import mauticor as mauticor
    app.register_blueprint(mauticor, url_prefix="/mauticor")

    from .bookie import bookie as bookie
    app.register_blueprint(bookie, url_prefix="/bookie")

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    return app
Beispiel #18
0
def create_application(config = None):
    global app

    # Flask!
    app = Flask(__name__)
    app.config.from_object('supysonic.config.DefaultConfig')

    if not config: # pragma: nocover
        config = IniConfig.from_common_locations()
    app.config.from_object(config)

    # Set loglevel
    logfile = app.config['WEBAPP']['log_file']
    if logfile: # pragma: nocover
        from logging.handlers import TimedRotatingFileHandler
        handler = TimedRotatingFileHandler(logfile, when = 'midnight')
        handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
        logger.addHandler(handler)
    loglevel = app.config['WEBAPP']['log_level']
    if loglevel:
        logger.setLevel(getattr(logging, loglevel.upper(), logging.NOTSET))

    # Initialize database
    init_database(app.config['BASE']['database_uri'])
    app.wsgi_app = db_session(app.wsgi_app)

    # Insert unknown mimetypes
    for k, v in app.config['MIMETYPES'].items():
        extension = '.' + k.lower()
        if extension not in mimetypes.types_map:
            mimetypes.add_type(v, extension, False)

    # Initialize Cache objects
    # Max size is MB in the config file but Cache expects bytes
    cache_dir = app.config['WEBAPP']['cache_dir']
    max_size_cache = app.config['WEBAPP']['cache_size'] * 1024**2
    max_size_transcodes = app.config['WEBAPP']['transcode_cache_size'] * 1024**2
    app.cache = Cache(path.join(cache_dir, "cache"), max_size_cache)
    app.transcode_cache = Cache(path.join(cache_dir, "transcodes"), max_size_transcodes)

    # Test for the cache directory
    cache_path = app.config['WEBAPP']['cache_dir']
    if not path.exists(cache_path):
        makedirs(cache_path) # pragma: nocover

    # Read or create secret key
    app.secret_key = get_secret_key('cookies_secret')

    # Import app sections
    if app.config['WEBAPP']['mount_webui']:
        from .frontend import frontend
        app.register_blueprint(frontend)
    if app.config['WEBAPP']['mount_api']:
        from .api import api
        app.register_blueprint(api, url_prefix = '/rest')

    return app
Beispiel #19
0
def create_app(queue, larigira):
    app = Flask('larigira')
    app.config.update(get_conf())
    Bootstrap(app)
    app.register_blueprint(rpc)
    app.register_blueprint(viewui)
    app.register_blueprint(db)
    app.queue = queue
    app.larigira = larigira
    app.cache = SimpleCache()
    return app
Beispiel #20
0
def create_app():
    logging.config.dictConfig(import_string('settings.LOGGING_CONFIG'))
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(settings)

    app.cache = RedisCache(host=settings.REDIS_HOST, port=settings.REDIS_PORT)

    # Register blueprint here
    app.register_blueprint(auth)

    return app
Beispiel #21
0
def create_app(config="app.config.Config"):
    app = Flask(__name__)

    # Set Config
    app.config.from_object(config)

    with app.app_context():
        # Create Database(if it doesn't created)
        url = create_database()

        # Set MySQL's charset to utf8mb4 forcely
        app.config["SQLALCHEMY_DATABASE_URI"] = str(url)

        # Set Redis Session
        app.session_interface = redis.RedisSessionInterface()

        # Register Database
        db.init_app(app)

        # Create DB Session & Engine (if db is not defined, create db too.)
        db.create_all()

        # Set ReCaptcha
        if is_setup():
            app.config["RECAPTCHA_SITE_KEY"] = get_config("recaptcha_site_key")
            app.config["RECAPTCHA_SECRET_KEY"] = get_config(
                "recaptcha_secret_key")

        recaptcha.init_app(app)

        # Initialization
        init_template_globals(app)
        init_request_processors(app)

        # Cache Initialization
        cache.init_app(app)
        app.cache = cache

        from app.admin import admin
        from app.handler import page_not_found, forbidden, general_error, gateway_error, too_many_requests

        app.register_blueprint(admin)

        # Error Handler
        app.register_error_handler(403, forbidden)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(429, too_many_requests)
        app.register_error_handler(500, general_error)
        app.register_error_handler(502, gateway_error)

        return app
def create_app(env=None):
    app = Flask("image_server")
    app.register_error_handler(404, handle_404)
    app.register_error_handler(BadRequest, bad_request)
    app.register_error_handler(Exception, unhandled)
    # start the cache manager daemon
    cache_manager_daemon = threading.Thread(target=cache_manager)
    cache_manager_daemon.daemon = True
    cache_manager_daemon.start()
    cache = before_start()
    app.cache = cache
    register_blueprints(app)

    return app
Beispiel #23
0
def create_app():
    app = Flask(__name__, static_folder=static_folder,
                template_folder=template_folder)
    app.debug = True

    # Configuration files
    app.config.from_pyfile(os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        '..', 'default_config.py'
    ))
    app.config.from_pyfile(os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        '..', 'config.py'
    ), silent=True)

    # Error handling
    import errors
    errors.init_error_handlers(app)

    # I18n
    import babel
    babel.init_app(app)

    # Caching
    from werkzeug.contrib.cache import SimpleCache
    app.cache = SimpleCache()

    # Template utilities
    app.jinja_env.add_extension('jinja2.ext.do')

    from website.expand import expand
    app.jinja_env.filters['expand'] = expand

    # Blueprints
    from views import frontend_bp
    from views.changelog import changelog_bp
    from views.humans import humans_bp
    from views.plugins import plugins_bp
    from views.docs import docs_bp
    from views.api import api_bp

    app.register_blueprint(frontend_bp)
    app.register_blueprint(changelog_bp, url_prefix='/changelog')
    app.register_blueprint(humans_bp)
    app.register_blueprint(plugins_bp, url_prefix='/plugins')
    app.register_blueprint(docs_bp, url_prefix='/docs')
    app.register_blueprint(api_bp, url_prefix='/api')

    return app
Beispiel #24
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
def create_app():
    app = Flask(__name__,
                static_folder=static_folder,
                template_folder=template_folder)
    app.debug = True

    # Configuration files
    app.config.from_pyfile(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), '..',
                     'default_config.py'))
    app.config.from_pyfile(os.path.join(
        os.path.dirname(os.path.realpath(__file__)), '..', 'config.py'),
                           silent=True)

    # Error handling
    import errors
    errors.init_error_handlers(app)

    # I18n
    import babel
    babel.init_app(app)

    # Caching
    from werkzeug.contrib.cache import SimpleCache
    app.cache = SimpleCache()

    # Template utilities
    app.jinja_env.add_extension('jinja2.ext.do')

    from website.expand import expand
    app.jinja_env.filters['expand'] = expand

    # Blueprints
    from views import frontend_bp
    from views.changelog import changelog_bp
    from views.humans import humans_bp
    from views.plugins import plugins_bp
    from views.docs import docs_bp
    from views.api import api_bp

    app.register_blueprint(frontend_bp)
    app.register_blueprint(changelog_bp, url_prefix='/changelog')
    app.register_blueprint(humans_bp)
    app.register_blueprint(plugins_bp, url_prefix='/plugins')
    app.register_blueprint(docs_bp, url_prefix='/docs')
    app.register_blueprint(api_bp, url_prefix='/api')

    return app
Beispiel #26
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
Beispiel #27
0
def create_app(app_name, config_obj, with_api=True):
    """ Generates and configures the main shop application. All additional """
    # Launching application
    app = Flask(app_name)  # So the engine would recognize the root package

    # Load Configuration
    app.config.from_object(config_obj)

    # Initializing Database
    db = SQLAlchemy(app)
    app.db = db

    # migrate = Migrate(app, db)

    app.cache = Cache(app)

    # Initializing Alembic
    alembic = Alembic()
    alembic.init_app(app)
    app.alembic = alembic

    moment = Moment(app)
    app.moment = moment

    # Initializing the restful API
    if with_api:
        api = Api(app, prefix='/rest')
        app.api = api

    # Initialize Logging
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler
        file_handler = RotatingFileHandler(
            "/var/log/locales/%s.log" %
            app.config.get("LOGFILE_NAME", app_name),
            maxBytes=500 * 1024)
        file_handler.setLevel(logging.INFO)
        from logging import Formatter
        file_handler.setFormatter(
            Formatter('%(asctime)s %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)

        # include an api_registry to the application
    app.api_registry = []  # a simple list holding the values to be registered

    return app
Beispiel #28
0
def create_app():
    conf = Config( )
    iggybase = Flask( __name__ )
    iggybase.config.from_object( conf )
    iggybase.cache = Cache()

    init_db( )

    configure_blueprints(iggybase)
    security, user_datastore = configure_extensions( iggybase, db )
    configure_error_handlers( iggybase )
    configure_hook( iggybase )

    add_base_routes( iggybase, conf, security, user_datastore )

    return iggybase
Beispiel #29
0
def create_app(message_queue_factory=MessageQueue, cache_factory=Cache):
    app = Flask(__name__)
    app.config.from_object(Configuration)

    app.cache = cache_factory(app.config["CACHE_HOST"],
                              app.config["CACHE_PORT"])
    app.message_queue = message_queue_factory(app.config["MQ_HOST"],
                                              app.config["MQ_PORT"],
                                              app.config["MQ_USER"],
                                              app.config["MQ_PASS"])
    app.message_queue.register_teardown(app)

    from .views import views
    app.register_blueprint(views)

    return app
Beispiel #30
0
def setup_cache(app: Flask) -> None:
    """
    Initiates memcached caching
    """

    try:
        app.cache = Client(
            app.config["MEMCACHED_SERVER"],
            serde=PickleSerde(pickle_version=2),
            connect_timeout=5,
            timeout=1,
            ignore_exc=True,
        )

    except Exception:
        app.logger.error("Error in setup cache", exc_info=True)
Beispiel #31
0
 def create_app(self):
     app = Flask(__name__, template_folder='../templates')
     app.config.from_object('config.TestConfig')
     app.json_encoder = AlchemyEncoder
     app.cache = CacheMock()
     app.cache_lock = LockMock()
     
     # configure assets to get templating to work
     assets = Environment(app)
     assets.register('core-js', Bundle())
     assets.register('core-css', Bundle())
     
     db.init_app(app)
     app.register_blueprint(megatrack)
     app.register_blueprint(lesion)
     return app
Beispiel #32
0
def create_app():
    logging.config.dictConfig(import_string("settings.LOGGING_CONFIG"))
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(settings)
    app.cache = Redis(
        host=settings.REDIS_HOST,
        port=settings.REDIS_PORT,
        db=settings.REDIS_DB,
        password=settings.REDIS_PASSWORD,
    ).get_connection()

    Limiter(app, key_func=get_remote_address, default_limits=["50 per minute"])

    register_route_blueprint(app)

    return app
Beispiel #33
0
def app(monkeypatch):
    mock_app = Flask(__name__)
    mock_app.api = Api(mock_app,
                       prefix='/api/v1',
                       errors=api_error_map,
                       catch_all_404s=True)
    mock_app.config['CACHE_TYPE'] = 'simple'
    mock_app.cache = Cache(mock_app)
    mock_app.testing = True
    mock_app.debug = True

    from nextbus.router import setup_router
    setup_router(mock_app)
    mock_app.stats_redis = mock_redis_client()
    mock_app.nextbus_api = NextbusApiClient()

    return mock_app
Beispiel #34
0
def create_app(config_file):
    app = Flask(__name__)

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_API_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar('XSNIPPET_API_SETTINGS', silent=True)

    app.register_blueprint(api)

    # create a database connection (it's thread-safe, so we can keep it global)
    app.db = create_db_connection(app)

    # create a cache connection (it's thread-safe too)
    app.cache = create_cache_connection(app, key_prefix="api_")

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

    app.register_blueprint(auth.mod_auth)
    app.register_blueprint(items.mod_items)
    app.register_blueprint(search.mod_search)
    app.register_blueprint(categories.mod_categories)
    app.register_blueprint(users.mod_users)
    app.add_url_rule('/', endpoint='entries.index')

    app.cache = Cache(app, config=cache_config)
    app.login = LoginManager()
    app.login.login_view = 'auth.login'
    babel.init_app(app)

    return app
Beispiel #36
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
Beispiel #37
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(UseConfig)
    app.cache = Cache(app)
    admin = Admin(app)
    admin.add_view(MyView(name='IpSet'))
    admin.add_view(IPModelView(models.IPINFO, db_session))
    admin.add_view(IpAreaView(models.AREA, db_session))
    admin.add_view(IpSegModelView(models.IPSEG, db_session))
    if not app.debug:  #非调试模式 运行邮件程序
        mail_handler = SMTPHandler('',
                                   '',
                                   ADMINS,
                                   'IP_verify code BUG',
                                   credentials=('', ''))
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    return app
def create_app(config_obj=None):
    app = Flask(__name__)

    app.config.update(load_config(config_obj))
    if app.config[
            'PRODUCTION'] and app.secret_key == 'replace-me-with-something-random':
        raise Warning(
            "You need to change the app.secret_key value for production")

    logging_config = app.config.get('LOGGING')
    if logging_config:
        logging.config.dictConfig(logging_config)

    policies_dir = app.config['POLICIES_DIR']
    log.debug("config: Loading policies from %r", policies_dir)
    app.config['policies'] = load_policies(policies_dir)

    subject_types_dir = app.config['SUBJECT_TYPES_DIR']
    log.debug("config: Loading subject types from %r", subject_types_dir)
    app.config['subject_types'] = load_subject_types(subject_types_dir)

    if app.config.get('DIST_GIT_URL_TEMPLATE') and app.config.get(
            'DIST_GIT_BASE_URL'):
        app.config['DIST_GIT_URL_TEMPLATE'] = app.config[
            'DIST_GIT_URL_TEMPLATE'].replace('{DIST_GIT_BASE_URL}',
                                             app.config['DIST_GIT_BASE_URL'])

    # register error handlers
    for code in default_exceptions.keys():
        app.register_error_handler(code, json_error)
    app.register_error_handler(ConnectionError, json_error)
    app.register_error_handler(requests.ConnectionError, json_error)
    app.register_error_handler(requests.Timeout, json_error)

    # register blueprints
    app.register_blueprint(api, url_prefix="/api/v1.0")
    app.register_blueprint(monitor_api, url_prefix="/api/v1.0")
    app.add_url_rule('/healthcheck', view_func=healthcheck)

    # Initialize the cache.
    app.cache = make_region(key_mangler=sha1_mangle_key)
    app.cache.configure(**app.config['CACHE'])

    return app
Beispiel #39
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(settings)

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

    redis_store.init_app(app)
    cache.init_app(app)
    app.cache = cache
    app.plugin_modules = plugin_modules

    slackbot = SlackBot(app)
    slackbot.set_handler(callback)
    slackbot.filter_outgoing(_filter)

    return app
Beispiel #40
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(settings)

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

    redis_store.init_app(app)
    cache.init_app(app)
    app.cache = cache
    app.plugin_modules = plugin_modules

    slackbot = SlackBot(app)
    slackbot.set_handler(callback)
    slackbot.filter_outgoing(_filter)

    return app
Beispiel #41
0
def create_app(package_name, package_path, debug=False):
    """Returns a :class:`Flask` application instance.
    :param package_name: application package name
    :param package_path: application package path
    :param debug: the debug flag
    """
    app = Flask(package_name, instance_relative_config=True)

    app.config.from_object('trexmo.settings')
    app.config.from_envvar('TREXMO_SETTINGS', silent=True)

    if debug:
        app.debug = debug

    app.db_engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    app.teardown_appcontext(remove_db_session)

    app.cache = Cache(app, config=app.config)

    register_blueprints(app, package_name, package_path)
    return app
Beispiel #42
0
def make_app(cache=None, config=None):

    if config is None:
        config = Config()

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

    if cache is None:
        cache = Cache(config=config)

    app.cache = cache

    # Get the fallback server from shotgun_api3_registry.
    passthrough_server = app.config.setdefault('PASSTHROUGH_SERVER', get_shotgun_kwargs(config)['base_url'].strip('/'))
    app.config.setdefault('PASSTHROUGH_URL', passthrough_server + '/api3/json')

    # We use one HTTP session for everything.
    app.http_session = requests.Session()

    # Register the logic.
    app.register_blueprint(blueprint)

    return app
Beispiel #43
0
def create_app(configuration_file = None):
	app = Flask(__name__)
	app.plugins = []

	# cannot use namespace here, weak signals will disappear
	app.plugin_signals = {
		'plugin-loaded': Signal(),
		'page-loaded': Signal(),
		'special-loaded': Signal(),
		'page-preprocess': Signal(),
		'page-postmarkdown': Signal(),
		'page-treeprocess': Signal(),
		'page-postprocess': Signal(),
	}

	# load a default config, and from configuration file
	app.config.from_object(defaults)
	if configuration_file:
		app.config.from_pyfile(configuration_file)

	app.db = WikiDb(app.config['REPOSITORY_PATH'])
	app.cache = Cache(app)

	app.register_module(frontend)

	# load plugins
	for plugin_name in app.config['PLUGINS']:
		import_name = 'qwappplugin.%s' % plugin_name

		qwappplugin = __import__('qwappplugin.%s' % plugin_name)
		plugin_module = getattr(qwappplugin, plugin_name)
		app.logger.debug('loading plugin %s' % plugin_module.plugin.version_string)

		plugin_module.plugin.register_app(app)

	return app
Beispiel #44
0
from flask import Flask, render_template, session, url_for, redirect, request, flash
import heroku
import oauth2 as oauth
import redis
import urlparse
from urllib import urlencode
import redis
import json
import random
import os

app = Flask(__name__)
app.secret_key = heroku.consumer_key
app.consumer = oauth.Consumer(key=heroku.consumer_key, secret=heroku.consumer_secret)
app.cache = redis.from_url(os.getenv('REDISTOGO_URL', 'redis://localhost'))
app.auth_url = heroku.auth_url
app.site_url = heroku.site_url
app.tweet_url = heroku.tweet_url
app.client = oauth.Client(app.consumer)

def verify_response(resp, content):
	if app.debug:
		with open(heroku.log_file, "a") as log:
			log.write(request.url+"\n")
			log.write("".join(["twitter response: ", str(resp), "\n"]))
			log.write("".join(["twitter content: ", content, "\n"]))
	if resp["status"] != "200":
		session.pop("access_token", None)
		session.pop("request_token", None)
		flash("Bad response from Twitter")	
		return redirect(url_for("index"))	
Beispiel #45
0
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache

from config import BaseConfig


app = Flask(__name__)
app.config.from_object(BaseConfig)
#cache = Cache(app, config={
#    'CACHE_TYPE': 'redis',
#    'CACHE_KEY_PREFIX': 'fcache',
#    'CACHE_REDIS_HOST': 'redis',
#    'CACHE_REDIS_PORT': '6379',
#    'CACHE_REDIS_URL': 'redis://redis:6379'
#    })
app.cache = Cache(app)
db = SQLAlchemy(app)
CORS(app)


class District(db.Model):
    __tablename__ = 'districts'
    id = db.Column(db.Integer, primary_key=True)
    statefp = db.Column(db.String)
    cd114fp = db.Column(db.String)
    geoid = db.Column(db.String)
    namelsad = db.Column(db.String)
    aland = db.Column(db.Float)
    awater = db.Column(db.Float)
    lat = db.Column(db.Float)
    lon = db.Column(db.Float)
# Assets
from flask.ext.assets import Environment
assets = Environment(app)
# Ensure output directory exists
assets_output_dir = os.path.join(FLASK_APP_DIR, 'static', 'gen')
if not os.path.exists(assets_output_dir):
    os.mkdir(assets_output_dir)

# Email
from flask.ext.mail import Mail
mail = Mail(app)

# Memcache
from werkzeug.contrib.cache import MemcachedCache
app.cache = MemcachedCache(app.config['MEMCACHED_SERVERS'])


def cache_fetch(key, value_function, timeout=None):
    '''Mimicking Rails.cache.fetch'''
    global app
    self = app.cache
    data = self.get(key)
    if data is None:
        data = value_function()
        self.set(key, data, timeout)
    return data
app.cache.fetch = cache_fetch


# Helpers
Beispiel #47
0
def create_app_ext(flask_config_file=None, flask_config_dict=None,
                   moin_config_class=None, warn_default=True, **kwargs):
    """
    Factory for moin wsgi apps

    :param flask_config_file: a flask config file name (may have a MOINCFG class),
                              if not given, a config pointed to by MOINCFG env var
                              will be loaded (if possible).
    :param flask_config_dict: a dict used to update flask config (applied after
                              flask_config_file was loaded [if given])
    :param moin_config_class: if you give this, it'll be instantiated as app.cfg,
                              otherwise it'll use MOINCFG from flask config. If that
                              also is not there, it'll use the DefaultConfig built
                              into MoinMoin.
    :param warn_default: emit a warning if moin falls back to its builtin default
                         config (maybe user forgot to specify MOINCFG?)
    :param kwargs: if you give additional keyword args, the keys/values will get patched
                   into the moin configuration class (before its instance is created)
    """
    clock = Clock()
    clock.start('create_app total')
    app = Flask('MoinMoin')
    clock.start('create_app load config')
    if flask_config_file:
        app.config.from_pyfile(flask_config_file)
    else:
        if not app.config.from_envvar('MOINCFG', silent=True):
            # no MOINCFG env variable set, try stuff in cwd:
            from os import path
            flask_config_file = path.abspath('wikiconfig_local.py')
            if not path.exists(flask_config_file):
                flask_config_file = path.abspath('wikiconfig.py')
                if not path.exists(flask_config_file):
                    flask_config_file = None
            if flask_config_file:
                app.config.from_pyfile(flask_config_file)
    if flask_config_dict:
        app.config.update(flask_config_dict)
    Config = moin_config_class
    if not Config:
        Config = app.config.get('MOINCFG')
    if not Config:
        if warn_default:
            logging.warning("using builtin default configuration")
        from MoinMoin.config.default import DefaultConfig as Config
    for key, value in kwargs.iteritems():
        setattr(Config, key, value)
    if Config.secrets is None:
        # reuse the secret configured for flask (which is required for sessions)
        Config.secrets = app.config.get('SECRET_KEY')
    app.cfg = Config()
    clock.stop('create_app load config')
    clock.start('create_app register')
    # register converters
    from werkzeug.routing import BaseConverter

    class ItemNameConverter(BaseConverter):
        """Like the default :class:`UnicodeConverter`, but it also matches
        slashes (except at the beginning AND end).
        This is useful for wikis and similar applications::

            Rule('/<itemname:wikipage>')
            Rule('/<itemname:wikipage>/edit')
        """
        regex = '[^/]+?(/[^/]+?)*'
        weight = 200

    app.url_map.converters['itemname'] = ItemNameConverter
    # register modules, before/after request functions
    from MoinMoin.apps.frontend import frontend
    frontend.before_request(before_wiki)
    frontend.teardown_request(teardown_wiki)
    app.register_blueprint(frontend)
    from MoinMoin.apps.admin import admin
    admin.before_request(before_wiki)
    admin.teardown_request(teardown_wiki)
    app.register_blueprint(admin, url_prefix='/+admin')
    from MoinMoin.apps.feed import feed
    feed.before_request(before_wiki)
    feed.teardown_request(teardown_wiki)
    app.register_blueprint(feed, url_prefix='/+feed')
    from MoinMoin.apps.misc import misc
    misc.before_request(before_wiki)
    misc.teardown_request(teardown_wiki)
    app.register_blueprint(misc, url_prefix='/+misc')
    from MoinMoin.apps.serve import serve
    app.register_blueprint(serve, url_prefix='/+serve')
    clock.stop('create_app register')
    clock.start('create_app flask-cache')
    cache = Cache()
    cache.init_app(app)
    app.cache = cache
    clock.stop('create_app flask-cache')
    # init storage
    clock.start('create_app init backends')
    init_backends(app)
    clock.stop('create_app init backends')
    clock.start('create_app flask-babel')
    i18n_init(app)
    clock.stop('create_app flask-babel')
    # configure templates
    clock.start('create_app flask-themes')
    setup_themes(app)
    if app.cfg.template_dirs:
        app.jinja_env.loader = ChoiceLoader([
            FileSystemLoader(app.cfg.template_dirs),
            app.jinja_env.loader,
        ])
    app.register_error_handler(403, themed_error)
    clock.stop('create_app flask-themes')
    clock.stop('create_app total')
    del clock
    return app
Beispiel #48
0
)

import memcache
from flask_memcache_session import Session
from werkzeug.contrib.fixers import ProxyFix

# git clone https://github.com/dart-lang/py-gfm.git
# cd py-gfm
# python setup.py install
from markdown import markdown

import json, os, hashlib, tempfile, subprocess
config = {}

app = Flask(__name__, static_url_path='')
app.cache = memcache.Client(['unix:/tmp/memcached.sock'], debug=0)
app.session_interface = Session()
app.session_cookie_name = "isucon_session"
app.wsgi_app = ProxyFix(app.wsgi_app)

# log
import logging
logging.basicConfig(filename='log.txt')
#logging.basicConfig(filename='log.txt', level=logging.DEBUG)

def load_config():
    global config
    print("Loading configuration")
    env = os.environ.get('ISUCON_ENV') or 'local'
    with open('../config/' + env + '.json') as fp:
        config = json.load(fp)
Beispiel #49
0
def create_retries_app(cache):
    retries_app = Flask(__name__)
    retries_app.PORT = 12
    retries_app.cache = cache

    # we want the retries app to listen on all methods
    retries_app.url_map.add(Rule('/', endpoint='index'))
    @retries_app.endpoint("index")
    def check_retries():
        json_hdr = {'Content-Type': 'application/json'}
        key = request.args.get('key', 'default')
        tries = request.args.get('tries', 3)
        try:
            tries = int(tries)
        except Exception:
            return Response(status=400, headers=json_hdr, response=json.dumps({
                'error': 'Please pass an integer number of tries',
                'key': key,
                'success': False,
            }))

        if key in retries_app.cache:
            retries_app.cache[key] -= 1
        else:
            retries_app.cache[key] = int(tries) - 1

        if retries_app.cache[key] <= 0:
            data = {
                'key': key,
                'tries_remaining': retries_app.cache[key],
                'success': True
            }
            return Response(response=json.dumps(data), status=200,
                            headers=json_hdr)
        else:
            msg = 'The server had an error. Try again {retry_times} more {time_p}'
            time_p = 'time' if retries_app.cache[key] == 1 else 'times'
            content = {
                'error': msg.format(retry_times=retries_app.cache[key], time_p=time_p),
                'tries_remaining': retries_app.cache[key],
                'key': key,
                'success': False,
            }
            return Response(response=json.dumps(content), status=500,
                            headers=json_hdr)

    @retries_app.route("/counters", methods=['POST'])
    def reset():
        key = request.values.get('key', 'default')
        tries = request.values.get('tries', 3)
        try:
            tries = int(tries)
        except Exception:
            return Response(status=400, headers=json_hdr, response=json.dumps({
                'error': 'Please pass an integer number of tries',
                'key': key,
                'success': False,
            }))

        retries_app.cache[key] = tries

        content = {
            'key': key,
            'tries_remaining': tries,
            'success': True,
        }
        return Response(response=json.dumps(content), status=200,
                        headers={'Content-Type': 'application/json'})

    @retries_app.route("/counters", methods=['GET'])
    def counter():
        content = {'counters': retries_app.cache, 'success': True}
        return Response(response=json.dumps(content), status=200,
                        headers={'Content-Type': 'application/json'})

    @retries_app.after_request
    def retries_header(resp):
        _log_flask(resp.status_code)
        resp.headers['Server'] = 'hamms'
        return resp

    return retries_app
Beispiel #50
0
    do_tweets = app.config["TWITTER_ENABLED"]
    tweeter = twitter.Api(
        consumer_key=app.config["TWITTER_KEY"],
        consumer_secret=app.config["TWITTER_SECRET"],
        access_token_key=app.config["TWITTER_TOKEN"],
        access_token_secret=app.config["TWITTER_TOKEN_SECRET"],
    )
    if not api.VerifyCredentials():
        tweeter = False
except:
    pass

# Memcache
from werkzeug.contrib.cache import MemcachedCache

app.cache = MemcachedCache(app.config["MEMCACHED_SERVERS"])


def cache_fetch(key, value_function, timeout=None):
    """Mimicking Rails.cache.fetch"""
    global app
    self = app.cache
    data = self.get(key)
    if data is None:
        data = value_function()
        self.set(key, data, timeout)
    return data


app.cache.fetch = cache_fetch
Beispiel #51
0
from flask import (
    Flask, request, redirect, session, url_for, abort,
    render_template, _app_ctx_stack, Response,
    after_this_request,
)

import memcache
from flask_memcache_session import Session
from werkzeug.contrib.fixers import ProxyFix

import json, os, hashlib, tempfile, subprocess

config = {}

app = Flask(__name__, static_url_path='')
app.cache = memcache.Client(['localhost:11211'], debug=0)
app.session_interface = Session()
app.session_cookie_name = "isucon_session_python"
app.wsgi_app = ProxyFix(app.wsgi_app)

def load_config():
    global config
    print("Loading configuration")
    env = os.environ.get('ISUCON_ENV') or 'local'
    with open('../config/' + env + '.json') as fp:
        config = json.load(fp)

def connect_db():
    global config
    host = config['database']['host']
    port = config['database']['port']
Beispiel #52
0
import oauth2 as oauth
import config
import urlparse
from flask import Flask, redirect, url_for, session, render_template, request, flash, make_response
from urllib import urlencode
import time
import json
import twitter
import redis

app = Flask(__name__)
app.secret_key = config.CKEY
app.consumer = oauth.Consumer(key=config.CKEY, secret=config.CSEC)
app.cache = redis.StrictRedis(host='localhost', port=6379, db=0)

def verify_response(resp):
	if resp['status'] != '200':
		session.pop('request_token', None)
		flash('Bad response from Twitter: {0}'.format(resp))
		return redirect(url_for('index'))
	else:
		return None

def get_tweets(client):
	'''Queries Twitter API for user tweets until it gets 0 back.
	Concatenates and returns tweets.'''
	tweets = []
	page = 1
	while True: # repeat until tweet supply is exhausted 
		url = config.API+'1/statuses/user_timeline.json?count=200&page={0}'.format(page)
		resp, content = client.request(url, 'GET', body=urlencode({
Beispiel #53
0
from flask import Flask, render_template, request
from pymongo import MongoClient
from flask.ext.cache import Cache

#Korean Analyzer
from konlpy.tag import Twitter
import json
from bson import json_util

app = Flask(__name__)
app.config['CACHE_TYPE'] = 'simple'
app.cache = Cache(app, config={
         'CACHE_TYPE': 'filesystem',
         'CACHE_DIR': 'cache-dir',
         'CACHE_DEFAULT_TIMEOUT': 922337203685477580,
         'CACHE_THRESHOLD': 922337203685477580
     })

@app.route("/")
def enter():
    client = MongoClient('mongodb://localhost:27017/')
    db = client.reviews
    collection = db.app
    data = list()
    appids = collection.distinct('appid')
    apptitles = collection.distinct('apptitle')
    infos = list()
    for idx, appid in enumerate(appids):
        info = (appid,apptitles[idx],int(apptitles[idx].split('.')[0]))
        infos.append(info)
    for row in sorted(infos, key=lambda x: x[2]):
Beispiel #54
0
# -*- coding: utf-8 -*-

__author__ = 'Glebov Boris'

from flask import Flask, render_template, session
from flask.ext.memcache_session import Session
from werkzeug.contrib.cache import MemcachedCache

import settings

# Modules
from modules import audio, vk_api

# Setup application
app = Flask(__name__)
app.cache = MemcachedCache([settings.MEMCACHED['host'], settings.MEMCACHED['port']])
app.session_interface = Session()

# Register modules
app.register_blueprint(audio.blueprint)
app.register_blueprint(vk_api.blueprint)

# Define basek url-handlers


@app.after_request
def after_request(response):
    response.headers.add('Accept-Ranges', 'bytes')
    return response

Beispiel #55
0
logger = logging.getLogger(__name__)
formatter = logging.Formatter(
        "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
# handler = TimedRotatingFileHandler('logs/foo.log', when='midnight', interval=1)
handler = RotatingFileHandler(app.config.get('LOG_FILENAME'),
                            maxBytes=app.config.get('LOG_FILESIZE'),
                            backupCount=1)
# handler.setLevel(logging.INFO)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
app.logger.addHandler(handler)
# log = logging.getLogger('werkzeug')
# log.setLevel(logging.DEBUG)
# log.addHandler(handler)

app.cache = redis.StrictRedis(**app.config.get('REDIS_CONFIG'))

app.cache.set("saDir", SA_DIR)
app.cache.set("uid_track", 1)
app.cache.set("session_data", {})

app.config['UPLOAD_FOLDER'] = os.path.dirname(os.path.abspath(__file__)) + SA_DIR
app.config['STATIC_FOLDER'] = os.path.dirname(os.path.abspath(__file__)) + '/static'

# app.session_interface = RedisSessionInterface(app.cache, key_prefix='SESSION')
app.session_interface = RedisSessionInterface(app.cache, key_prefix='SESSION',
                                            use_signer=True, permanent=False)
app.permanent_session_lifetime = datetime.timedelta(hours=1)

try:
    os.mkdir(SA_DIR)
Beispiel #56
0
    mail_handler.setFormatter(logging.Formatter('''
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s

Message:

%(message)s
'''))
    app.logger.addHandler(mail_handler)

if 'REDISTOGO_URL' in os.environ:
    redis_client = redis.from_url(os.environ['REDISTOGO_URL'])
    app.cache = RedisCache(redis_client)
else:
    app.cache = SimpleCache()

app.config['S3_BUCKET_NAME'] = 'radlibs-assets'
app.config['S3_USE_CACHE_CONTROL'] = False
app.config['S3_CDN_DOMAIN'] = 'd2hwb9ozcl9dk9.cloudfront.net'
app.config['FLASK_ASSETS_USE_S3'] = True
app.config['USE_S3_DEBUG'] = True
if os.getenv('ASSETS_DEBUG'):
    app.config['ASSETS_DEBUG'] = True
    app.config['FLASK_ASSETS_USE_S3'] = False
FlaskS3(app)
assets = Environment(app)
js = Bundle('js/jquery.min.js',
            'js/bootstrap.min.js',
Beispiel #57
0
Bootstrap(app)
login_manager = LoginManager()
login_manager.init_app(app)

DEFAULT_CALLBACK_PATH = app.config['DEFAULT_CALLBACK_PATH']
HOST = app.config['HOST']  # This host's name
CLIENT_SECRET = app.config['CLIENT_SECRET']  # Client Secret
CLIENT_ID = app.config['CLIENT_ID']  # Client ID
REALM = app.config['REALM']  # Keycloak realm
OIDC_HOST = app.config['OIDC_HOST']  # Keycloak host
OIDC_INFO_URL = '{:s}/auth/realms/{:s}/'.format(OIDC_HOST, REALM)
OIDC_REDIRECT_URI = 'http://{:s}/{:s}'.format(HOST, DEFAULT_CALLBACK_PATH)


# Initialize Cache
app.cache = Cache(app, config={'CACHE_TYPE': 'simple'})

# initialize components
from models import User

db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter=db_adapter, app=app, login_manager=login_manager)

import views

from um import um

app.register_blueprint(um)

from cm import cm
Beispiel #58
0
from flask import render_template
from flask import request
from flask.ext.mobility import Mobility
from werkzeug.contrib.cache import FileSystemCache
from werkzeug.contrib.fixers import ProxyFix

from discograph import api
from discograph import ui
from discograph import exceptions


app = Flask(__name__)
app.config.from_object('discograph.config.DevelopmentConfiguration')
app.cache = FileSystemCache(
    app.config['FILE_CACHE_PATH'],
    default_timeout=app.config['FILE_CACHE_TIMEOUT'],
    threshold=app.config['FILE_CACHE_THRESHOLD'],
    )
if not os.path.exists(app.config['FILE_CACHE_PATH']):
    os.makedirs(app.config['FILE_CACHE_PATH'])
app.register_blueprint(api.blueprint, url_prefix='/api')
app.register_blueprint(ui.blueprint)
app.wsgi_app = ProxyFix(app.wsgi_app)
Mobility(app)


@app.after_request
def inject_rate_limit_headers(response):
    try:
        requests, remaining, reset = map(int, g.view_limits)
    except (AttributeError, ValueError):