Beispiel #1
0
#!/usr/bin/env python
# -*- 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/.
'''This module powers the webcompat.com Flask application.'''

import os

from flask.ext.cache import Cache
from flask.ext.github import GitHub
from flask.ext.limiter import Limiter
from flask import Flask
from sqlalchemy import create_engine

app = Flask(__name__, static_url_path='')
app.config.from_object('config')
engine = create_engine('sqlite:///' +
                       os.path.join(app.config['BASE_DIR'], 'session.db'))

cache = Cache(app)
github = GitHub(app)
limiter = Limiter(app)

# import views after we initialize our github object
import webcompat.views

# register API blueprint
from api.endpoints import api
app.register_blueprint(api)
Beispiel #2
0
def create_app():
    """ Set up the Flask app, cache, read app configuration file, and
    other things.
    """
    import conf as configs

    from morpholex import MorphoLexicon

    # TODO: this is called twice sometimes, slowdowns have been reduced,
    # but don't know why yet. Need to check. It only happens on the
    # first POST lookup, however...

    with open(os.environ['NDS_CONFIG'], 'r') as F:
        static_prefix = yaml.load(F).get('ApplicationSettings').get('fcgi_script_path', '')

    os.environ['PATH'] += os.pathsep + os.path.join(os.path.dirname(__file__), 'node_modules/.bin')

    app = Flask(__name__,
                static_url_path=static_prefix+'/static',
                template_folder=cwd('templates'))

    app = jinja_options_and_filters(app)
    app.production = False

    DEFAULT_CONF = os.path.join(os.path.dirname(__file__),
                                'configs')

    app.config['cache'] = cache
    # TODO: make sure this isn't being specified by an env variable
    app.config['NDS_CONFDIR'] = os.environ.get('NDS_CONFDIR', DEFAULT_CONF)
    app.config['jinja_env'] = app.jinja_env

    app.config = Config('.', defaults=app.config)
    app.config.from_envvar('NDS_CONFIG')
    app.config.overrides = configs.blueprint.load_language_overrides(app)
    app.config.prepare_lexica()
    app.config.add_optional_routes()

    os.environ['NDS_PATH_PREFIX'] = app.config.fcgi_script_path
    app.static_url_path = app.config.fcgi_script_path + app.static_url_path

    # Prepare assets before custom templates are read
    app = prepare_assets(app)

    # Register rate limiter
    limiter = Limiter(app, global_limits=["120/minute"])
    app.limiter = limiter
    app.config['APPLICATION_ROOT'] = app.config.fcgi_script_path

    # Register language specific config information
    import views
    app.register_blueprint(views.blueprint, url_prefix=app.config['APPLICATION_ROOT'])
    app.register_blueprint(configs.blueprint, url_prefix=app.config['APPLICATION_ROOT'])

    # Prepare cache
    cache_path = os.path.join(os.path.dirname(__file__), 'tmp/generator_cache/%s/' % app.config.short_name)
    cache.init_app(app, {'CACHE_TYPE': 'filesystem', 'CACHE_DIR': cache_path})

    app.cache = cache

    with app.app_context():
        app.cache.clear()

    app.config['cache'] = cache

    app.morpholexicon = MorphoLexicon(app.config)

    from paradigms import ParadigmConfig

    pc = ParadigmConfig(app)
    app.morpholexicon.paradigms = pc

    ## Read and prepare the templates

    from entry_template_filters import register_template_filters
    from entry_templates import TemplateConfig

    app = register_template_filters(app)
    app.lexicon_templates = TemplateConfig(app, debug=True)

    try:
        with open('secret_key.do.not.check.in', 'r') as F:
            key = F.readlines()[0].strip()
        app.config['SECRET_KEY'] = key
    except IOError:
        print >> sys.stderr, """
        You need to generate a secret key, and store it in a file with the
        following name: secret_key.do.not.check.in """
        sys.exit()

    app = register_babel(app)
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler('127.0.0.1',
                                   '*****@*****.**',
                                   ADMINS, 'NDS error')
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    
    from logging import FileHandler
    from logging.handlers import SMTPHandler
    from socket import gethostname

    if app.debug:
        mail_handler = FileHandler('debug_email_log.txt')
    else:
        _admins = ADMINS + app.config.admins
        mail_handler = SMTPHandler('127.0.0.1',
                                   "server-error@%s" % gethostname(),
                                   ADMINS, "NDS-%s Failed" %  app.config.short_name)
        app.logger.smtp_handler = mail_handler

    # Templates are read, register the assets
    register_assets(app)

    mail_handler.setLevel(logging.ERROR)

    app.logger.addHandler(mail_handler)

    return app
Beispiel #3
0
import logging

from flask import Flask, request, render_template, make_response
from flask.ext.limiter import Limiter

from blocklister import __version__, __changelog__
from blocklister.models import Blocklist
from blocklister.config import Config
from blocklister.exc import FetcherException, EmptyListError
from blocklister.summerizer import Summerizer

LOG = logging.getLogger(__name__)
app = Flask(__name__)
limiter = Limiter(app, headers_enabled=True)
config = Config()
store = config.get('blocklister', 'store', default="/tmp")
dedupe = config.get_boolean('blocklister', 'deduplicate', default=False)


@app.errorhandler(IOError)
def handle_filenotavailable(exc):
    msg = "File on disk is not available"
    response = make_response(msg, 500)
    response.headers['Content-Type'] = "text/plain"
    return response


@app.errorhandler(ValueError)
def handle_unknown_blacklist(exc):
    routes = ["/%s" % x.__name__.lower() for x in Blocklist.__subclasses__()]
    msg = render_template(
Beispiel #4
0
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.limiter import Limiter
from flask.ext.cache import Cache
from flask.ext.pymongo import PyMongo

from app.config import config

bootstrap = Bootstrap()
limiter = Limiter()
cache = Cache()
mongo = PyMongo()


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

    bootstrap.init_app(app)
    limiter.init_app(app)
    cache.init_app(app)
    mongo.init_app(app)

    from app.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app