Exemple #1
0
def setup(app):
    # public configs, from config.yaml
    with open('config.yaml', 'r') as config_file:
        app.config.update(yaml.load(config_file))

    app.config['DEBUG'] = distutils.util.strtobool(ENV.get('DEBUG', 'False'))

    # extensions
    flask_misaka.Misaka(app)
    flask_scss.Scss(app, static_dir='static', asset_dir='static')
    cache = flask_cache.Cache(app, config={'CACHE_TYPE': 'simple'})

    return cache
Exemple #2
0
    if key in app.config:
        return app.config[key]
    else:
        if key in config.defaults:
            return config.defaults[key]
        else:
            app.logger.error('Tried to lookup missing config setting: %s' %
                             key)
            return None


# Setup caching
cache = flask_cache.Cache(app,
                          config={
                              'CACHE_TYPE': 'filesystem',
                              'CACHE_DIR': '/tmp',
                              'CACHE_THRESHOLD': 25000,
                              'CACHE_DEFAULT_TIMEOUT': 60,
                          })

# Setup openid
oid = flask_openid.OpenID(app)

# Setup database connection
db = flask_sqlalchemy.SQLAlchemy(app)
from .models import User, Team, GameServer, Match, Tournament, MapStats, PlayerStats  # noqa: E402
migrate = flask_migrate.Migrate(app, db)

# Setup rate limiting
limiter = flask_limiter.Limiter(
    app,
Exemple #3
0
"""dnstwister web app."""
import flask
import flask_cache

app = flask.Flask(__name__)
cache = flask_cache.Cache(app, config={'CACHE_TYPE': 'simple'})

import views.index
Exemple #4
0
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import uuid

import flask
import flask_cache

import backend_common.dockerflow
import cli_common.log

logger = cli_common.log.get_logger(__name__)
cache = flask_cache.Cache()


def init_app(app):
    cache_config = app.config.get('CACHE', {'CACHE_TYPE': 'simple'})
    cache.init_app(app, config=cache_config)
    return cache


def app_heartbeat():
    cache_key = str(uuid.uuid4().get_hex().upper()[0:6])
    cache_value = str(uuid.uuid4().get_hex().upper()[0:6])
    try:
        cache = flask.current_app.cache
        assert cache.cache.get(cache_key) is None
        assert cache.cache.set(cache_key, cache_value) is True
        assert cache.cache.get(cache_key) == cache_value
Exemple #5
0
    def __init(self, instance):
        instance.config.from_envvar('FLASK_SETTING')
        self.settings = instance.config
        if instance.debug:
            current = os.path.dirname(__file__)
            self.path = os.path.join(current, '..', 'dump', 'data')
            self.lpath = os.path.join(current, '..', 'dump', 'logs')
        else:
            self.path = os.path.join('/', 'var', 'rere1')
            self.lpath = os.path.join('/', 'var', 'logs')
            instance.wsgi_app = \
                werkzeug.contrib.fixers.ProxyFix(instance.wsgi_app)
            self.sentry = raven.contrib.flask.Sentry(
                instance,
                logging=True,
                level=logging.WARNING,
            )

        const = base.Constant
        with instance.app_context():
            for _ in range(0,
                           self.settings[const.SETTING_MAX_RECONNECTION_TRY]):
                try:
                    self.db = base.Alchemy
                    self.db.init_app(instance)
                    self.db.create_all()
                    self.db.session.commit()
                    break
                except Exception as exception:
                    time.sleep(self.settings[const.SETTING_DEFAULT_SLEEP_TIME])

            self.redis = flask_redis.FlaskRedis()
            self.redis.init_app(instance, decode_responses=True)

            for _ in range(0,
                           self.settings[const.SETTING_MAX_RECONNECTION_TRY]):
                try:
                    if self.redis.ping():
                        break
                    else:
                        raise Exception()
                except Exception as exception:
                    time.sleep(self.settings[const.SETTING_DEFAULT_SLEEP_TIME])

            flask_cors.CORS(instance)

            self.extensions = {}
            self.extensions['mail'] = flask_mail.Mail()
            self.extensions['mail'].init_app(instance)
            remote = flask_limiter.util.get_remote_address
            self.extensions['limiter'] = flask_limiter.Limiter(key_func=remote)
            self.extensions['limiter'].init_app(instance)
            self.extensions['cache'] = flask_cache.Cache(with_jinja2_ext=False)
            self.extensions['cache'].init_app(instance)

        if not instance.debug:
            for name, exception in werkzeug.exceptions.__dict__.items():
                if isinstance(exception, type):
                    if issubclass(exception, Exception):
                        instance.register_error_handler(
                            exception,
                            lambda exception: flask.jsonify({}),
                        )

        if not instance.debug:
            instance.logger.removeHandler(flask.logging.default_handler)
            handler = logging.FileHandler(os.path.join(self.lpath,
                                                       'api.log'), )
            handler.setLevel(logging.WARNING)
            instance.logger.addHandler(handler)

        self.__components = {}
        for name, component in components.__dict__.items():
            if isinstance(component, type):
                if issubclass(component, base.Component):
                    self.__components[name.lower()] = component(self)

        self.__actions = {}
        for name, action in actions.__dict__.items():
            if isinstance(action, type):
                if issubclass(action, base.Action):
                    self.__actions[name.lower()] = action(self)

        for name, command in commands.__dict__.items():
            if isinstance(command, type):
                if issubclass(command, base.Command):
                    cmd = functools.partial(command.execute, command(self))
                    cmd.__name__ = command.NAME
                    cmd = click.command()(cmd)
                    cmd.short_help = command.DESCRIPTION
                    for argument in command.ARGUMENTS:
                        cmd = click.option(
                            '--' + argument['name'],
                            type=argument['type'],
                            default=argument['default'],
                            help=argument['description'],
                        )(cmd)
                    instance.cli.add_command(cmd)
Exemple #6
0
        else:
            return render_template('oauth-failure.html')
    else:
        print(json.dumps(response, indent=4))
        return render_template('oauth-failure.html')


@app.route('/oauth-delete/', methods=['GET'])
def oauth_delete():
    try:
        context = {
            'weeks': request.args.get('weeks'),
            'api_token': request.args.get('api_token')
        }
        return render_template('ouath-success-success.html', **context)
    except KeyError:
        return render_template('oauth-failure.html')


if __name__ == '__main__':
    LOCAL = os.environ.get('LOCAL', False)
    cache = flask_cache.Cache(app,
                              config={
                                  'CACHE_TYPE': 'simple',
                                  'CACHE_DEFAULT_TIMEOUT': 10 * 60
                              })
    if not LOCAL:
        app.run('0.0.0.0', 8080)
    else:
        app.run()