Esempio n. 1
0
def create_app(debug=False):
    """Create an application context with blueprints."""
    app = Flask(__name__, static_folder='./resources')
    app.config['SECRET_KEY'] = 'RYVl4Fg3n1JLDaxWyr1m'
    app.config['MONGO_DBNAME'] = 'chirp'
    app.config['USERS_COLLECTION'] = 'accounts'
    app.config['MONITORS_COLLECTION'] = 'monitors'
    app.config['ARTICLES_COLLECTION'] = 'articles'
    app.config['GLOBAL_COLLECTION'] = 'global'
    login_manager.init_app(app)
    mongo.init_app(app)
    app.config.update(
        CELERY_BROKER_URL='redis://localhost:6379',
        CELERY_RESULT_BACKEND='redis://localhost:6379',
        CELERYBEAT_SCHEDULE={
            # 'heartbeat': {
            #     'task': 'heartbeat',
            #     'schedule': crontab(minute='*')
            # },
            'process_all_rss': {
                'task': 'process_all_rss',
                'schedule': crontab(minute='*/15')
            }
        })
    celery.conf.update(app.config)

    from .core import core as core_blueprint
    app.register_blueprint(core_blueprint)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, server_error)

    return app
Esempio n. 2
0
def init_app(app):
    """
    Registers above custom function (error_handler) as error handler
    for any Werkzeug error class, as well as other exceptions
    """
    # Werkzeug, see https://werkzeug.palletsprojects.com/en/1.0.x/exceptions/
    for exception in default_exceptions:
        app.register_error_handler(exception, error_handler)
    # Other exceptions
    app.register_error_handler(Exception, error_handler)
Esempio n. 3
0
def create_app(debug=False):
    """Create an application context with blueprints."""
    state = housekeeping()
    if not state:
        sys.exit(1)
    app = Flask(__name__, static_folder='./resources')
    app.config['SECRET_KEY'] = 'tRSn3mh2bY3@1$W2T9aQ'
    app.config['MONGO_DBNAME'] = 'netinfo'
    app.config['MONGO_HOST'] = 'localhost'
    app.config['ASNDB'] = None
    app.config['GEOIPDB'] = None
    app.config['DEBUG'] = debug
    muri = "mongodb://%s:27017/%s" % (app.config['MONGO_HOST'],
                                      app.config['MONGO_DBNAME'])
    app.config['MONGO_URI'] = muri
    mongo.init_app(app)
    app.config.update(CELERY_BROKER_URL='redis://localhost:6379',
                      CELERY_RESULT_BACKEND='redis://localhost:6379',
                      CELERYBEAT_SCHEDULE={
                          'fetch-rib': {
                              'task': 'fetch-rib',
                              'schedule': crontab(minute='*/5')
                          },
                          'fetch-as-name': {
                              'task': 'fetch-as-names',
                              'schedule': crontab(hour="*/12")
                          },
                          'fetch-geo': {
                              'task': 'fetch_geoip',
                              'schedule': crontab(hour=7,
                                                  minute=30,
                                                  day_of_week=1)
                          }
                      })
    celery.conf.update(app.config)

    config_file = '%s/resources/config.json' % APP_BASE
    if not os.path.exists(config_file):
        config = {
            'asn': {
                'last_rib_file': None,
                'last_update': None
            },
            'geoip': {
                'last_update': None
            }
        }
        json.dump(config, open(config_file, 'w'), indent=4)

    from .core import core as core_blueprint
    app.register_blueprint(core_blueprint)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, server_error)

    return app
Esempio n. 4
0
def init_app():
    """注册异常捕获"""
    # @app.errorhandler(404)
    # def resource_not_found(e):
    #     return jsonify(error=str(e)), 404

    app.register_error_handler(Exception, _handle_exception)
    app.register_error_handler(InternalServerError, _handle_serverexception)
    app.register_error_handler(HTTPException, _handle_httpexception)
    app.register_error_handler(404, _handle_404)
    app.register_error_handler(InvalidUsage, _handle_invalid)
Esempio n. 5
0
def create_app():

    # logging.getLogger("socketio").setLevel(logging.WARNING)
    # logging.getLogger("engineio").setLevel(logging.WARNING)
    # logging.getLogger("werkzeug").setLevel(logging.WARNING)
    #
    # for handler in logging.root.handlers:
    #     # Filter must be added to the handlers, because if added to a logger it
    #     # does not propagate: https://docs.python.org/3/library/logging.html#filter-objects
    #     handler.addFilter(UserRequestFilter())

    app = Flask('server/flask_server')
    app.name = 'flask_server'
    app.config["SECRET_KEY"] = '123secret'

    socketio.init_app(app, cors_allowed_origins="*")

    with app.app_context():
        from .views import auth, client

        app.register_error_handler(Exception, _uncaught_exception_handler)
        return app
Esempio n. 6
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('moin')

    if OldSecureCookieSessionInterface:
        app.session_interface = OldSecureCookieSessionInterface()

    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 moin.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 moin.apps.frontend import frontend
    frontend.before_request(before_wiki)
    frontend.teardown_request(teardown_wiki)
    app.register_blueprint(frontend)
    from moin.apps.admin import admin
    admin.before_request(before_wiki)
    admin.teardown_request(teardown_wiki)
    app.register_blueprint(admin, url_prefix='/+admin')
    from moin.apps.feed import feed
    feed.before_request(before_wiki)
    feed.teardown_request(teardown_wiki)
    app.register_blueprint(feed, url_prefix='/+feed')
    from moin.apps.misc import misc
    misc.before_request(before_wiki)
    misc.teardown_request(teardown_wiki)
    app.register_blueprint(misc, url_prefix='/+misc')
    from moin.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-theme')
    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-theme')
    clock.stop('create_app total')
    del clock
    return app
Esempio n. 7
0
File: app.py Progetto: Ictp/indico
def add_handlers(app):
    app.register_error_handler(404, handle_404)
    app.register_error_handler(Exception, handle_exception)
Esempio n. 8
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
Esempio n. 9
0
def add_handlers(app):
    app.register_error_handler(404, handle_404)
    app.register_error_handler(Exception, handle_exception)