Beispiel #1
0
def create_app(config=None):
    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app, querystring_param="_method")
    config = config or os.environ.get("HIPTWEET_CONFIG") or "default"
    app.config.from_object(expand_config(config))

    configure_logger(app)
    sentry.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    create_celery_app(app)
    if not app.debug:
        SSLify(app)

    from .oauth import twitter_bp
    app.register_blueprint(twitter_bp, url_prefix="/login")

    from .descriptors import descriptors as descriptors_blueprint
    app.register_blueprint(descriptors_blueprint)

    from .ui import ui as ui_blueprint
    app.register_blueprint(ui_blueprint)

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

    from .tasks import tasks as tasks_blueprint
    app.register_blueprint(tasks_blueprint)

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

        app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
        app.wsgi_app = HeaderRewriterFix(app.wsgi_app, remove_headers=['Date'], add_headers=[('X-Powered-By', 'WSGI'), ('Server', 'Noname Server')])

        return app
Beispiel #3
0
def create_app(name = __name__):
    app = Flask(__name__, static_path='/static')
    load_config(app)
    babel.init_app(app)
    #cache.init_app(app)

    db.init_app(app)
    filters.init_app(app)
    register_local_modules(app)

    app.wsgi_app = ProxyFixupHelper(app.wsgi_app)

    # Enable the DebugToolbar
    if app.config['DEBUG_TOOLBAR']:
        toolbar = DebugToolbarExtension(app)

    # Always attempt to set a BrowserId. At some point this will get used,
    # but let's start setting it now.
    app.wsgi_app = BrowserIdMiddleware(
        app.wsgi_app, secret_key=app.config['BROWSER_SECRET_KEY'],
        cookie_name='b', cookie_path='/',
        cookie_domain=None, cookie_lifetime=86400 * 365 * 10,
        cookie_secure=None, vary=())

    return app
Beispiel #4
0
def janitor_factory(options, auth_options):
    app = Flask(__name__)

    @app.route('/', methods=['GET'])
    @app.route('/<path:path>', methods=['GET'])
    def serve(path=options['default']):
        return send_from_directory(options['base_dir'], path)

    if auth_options['service'].lower() == 'github':
        if 'allowed_orgs' in auth_options:
            service = GithubService(allowed_orgs=auth_options['allowed_orgs'])
        else:
            service = GithubService()
    else:
        raise NotImplementedError()

    client = service.make_client(
        client_id=auth_options['client_id'],
        client_secret=auth_options['client_secret'],
    )

    app.wsgi_app = client.wsgi_middleware(app.wsgi_app,
                                          secret=options['secret_key'])
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.wsgi_app = ELBPingPong(app.wsgi_app)
    return app
Beispiel #5
0
def create_app():
    """Create Flask app."""
    config = load_config()

    if config.DEBUG or config.TESTING:
        app = Flask(__name__)
    else:
        app = Flask(__name__, template_folder=os.path.join(project_path, 'output/templates'))

    app.config.from_object(config)

    if not hasattr(app, 'production'):
        app.production = not app.debug and not app.testing

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    # Log errors to stderr in production mode
    if app.production:
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        # Enable Sentry
        if app.config.get('SENTRY_DSN'):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get('SENTRY_DSN'))

        # Serve static files during production
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/': os.path.join(project_path, 'output')
        })
    else:
        DebugToolbarExtension(app)

        # Serve static files during development
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/uploads': os.path.join(app.config.get('PROJECT_PATH'), 'uploads')
        })

    # Register components
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_uploadsets(app)
    register_hooks(app)

    return app
Beispiel #6
0
def create_app():
    """Create Flask app."""
    config = load_config()

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

    admin = Admin(app, name='microblog', template_mode='bootstrap3')
    # Add administrative views here

    if not hasattr(app, 'production'):
        app.production = not app.debug and not app.testing

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    if app.debug or app.testing:
        DebugToolbarExtension(app)

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/pages': os.path.join(app.config.get('PROJECT_PATH'), 'application/pages')
        })
    else:
        # Log errors to stderr in production mode
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        # Enable Sentry
        if app.config.get('SENTRY_DSN'):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get('SENTRY_DSN'))

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/static': os.path.join(app.config.get('PROJECT_PATH'), 'output/static'),
            '/pkg': os.path.join(app.config.get('PROJECT_PATH'), 'output/pkg'),
            '/pages': os.path.join(app.config.get('PROJECT_PATH'), 'output/pages')
        })

    # Register components
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_hooks(app)

    return app
Beispiel #7
0
def create_app():
    """Create Flask app."""
    config = load_config()

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

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    if app.debug or app.testing:
        DebugToolbarExtension(app)

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app, {"/pages": os.path.join(app.config.get("PROJECT_PATH"), "application/pages")}
        )
    else:
        # Log errors to stderr in production mode
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        # Enable Sentry
        if app.config.get("SENTRY_DSN"):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get("SENTRY_DSN"))

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {
                "/static": os.path.join(app.config.get("PROJECT_PATH"), "output/static"),
                "/pkg": os.path.join(app.config.get("PROJECT_PATH"), "output/pkg"),
                "/pages": os.path.join(app.config.get("PROJECT_PATH"), "output/pages"),
            },
        )

    # Register components
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_hooks(app)

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

    app.register_blueprint(home.bp)
    app.register_blueprint(sse, url_prefix='/stream')
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app, OrderedDict((
        ('/j', json_api),
    )))
    app.add_url_rule('/uploads/<filename>', 'uploaded_file',
                     build_only=True)
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
        '/uploads':  app.config['UPLOAD_FOLDER']
    })
    return app
Beispiel #9
0
def create_app():
    """Create the Flask app."""

    app = Flask("modelconvert")
    app.config.from_object('modelconvert.settings')
    app.config.from_envvar('MODELCONVERT_SETTINGS', silent=True)

    configure_logging(app)

    app.register_blueprint(frontend)

    celery.add_defaults(app.config)

    # configure error handlers
    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template("403.html"), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template("500.html"), 500


    if app.config['DEBUG']:
        from werkzeug.wsgi import SharedDataMiddleware
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/preview': app.config["DOWNLOAD_PATH"]
        })

    return app
Beispiel #10
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 #11
0
def create_app(config):
    global app
    app = Flask(
        __name__,
        template_folder='../templates',
        static_folder='../static'
    )
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config.update(config)

    app.url_rule_class = GeneratorRule

    app.redis = redis.Redis.from_url(config['REDISCLOUD_URL'])

    import views
    import login
    import login_oauth
    import talks
    import program
    import entrant
    import vote
    import filters
    import presenters_go
    import service
    return app
Beispiel #12
0
def create_app(config_object=DevConfig):
    config = CWRValidatorConfiguration().get_config()

    app = Flask(__name__)
    api = Api(app)

    app.config.from_object(config_object)

    _register_resources(api)
    _load_services(app, config)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    if app.config['DEBUG']:
        log = config['log.folder']
        if len(log) == 0:
            log = 'mera_ws.log'

        handler = RotatingFileHandler(log, maxBytes=10000, backupCount=1)
        handler.setLevel(logging.DEBUG)
        handler.setFormatter(
            Formatter('[%(levelname)s][%(asctime)s] %(message)s'))

        logging.basicConfig(level=logging.DEBUG)
        logging.getLogger('').addHandler(handler)

        app.logger.addHandler(handler)

    return app
Beispiel #13
0
def create_app(config):
    global app
    app = Flask(
        __name__,
        template_folder='../templates',
        static_folder='../static',
    )
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config.update(config)

    app.url_rule_class = GeneratorRule

    app.redis = redis.Redis.from_url(config['REDISCLOUD_URL'])
    app.eventee = {
        'token': config['EVENTEE_TOKEN'],
        'email': config['EVENTEE_EMAIL'],
    }

    from . import views
    from . import login
    from . import login_oauth
    from . import talks
    from . import program
    from . import entrant
    from . import vote
    from . import filters
    from . import service
    from . import workshops
    from . import invoices

    from .admin import admin

    app.register_blueprint(admin, url_prefix='/admin')
    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 _app_name_ 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)

    app.config.from_object('_app_name_.settings')
    app.config.from_pyfile('settings.cfg', silent=True)
    app.config.from_object(settings_override)

    db.init_app(app)
    mail.init_app(app)
    security.init_app(app, SQLAlchemyUserDatastore(db, User, Role),
                      register_blueprint=register_security_blueprint)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #15
0
def create_app(config=None, app_name=None, blueprints=None):
    """Create a Flask app."""

    if app_name is None:
        app_name = DefaultConfig.PROJECT
    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    app = Flask(app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True)
    app.wsgi_app = ReverseProxied(app.wsgi_app)

    configure_app(app, config)
    configure_hook(app)
    configure_blueprints(app, blueprints)
    configure_extensions(app)
    configure_logging(app)
    configure_template_filters(app)
    configure_error_handlers(app)

    appsocket = create_decoder_socket(app)
    decoder = Decoder(app, appsocket)
    manager = Manager(app)
    app.decoder = decoder

    return app, appsocket
Beispiel #16
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    bootstrap.init_app(app)

    db.init_app(app)
    security.init_app(app, user_datastore)
    toolbar.init_app(app)

    log_level = os.environ.get('LOG_LEVEL', 'INFO')
    logger = logging.getLogger(__name__)
    logger.setLevel(logging_map[log_level])
    stream = logging.StreamHandler()
    stream.setLevel(logging_map[log_level])
    logger.addHandler(stream)

    if config_name in ('docker', 'development', 'production'):
        sentry.init_app(app, logging=True, level=logging.INFO)
        app.wsgi_app = ProxyFix(app.wsgi_app)

    from app.celery import celery
    celery.conf.update(app.config)

    from .main import main
    app.register_blueprint(main)

    from .admin import admin
    admin.init_app(app)

    from .api_0_1 import api as api_0_1_blueprint
    app.register_blueprint(api_0_1_blueprint, url_prefix='/api/0.1')

    return app
Beispiel #17
0
def create_app(*, debug=False, threads=1, bigchaindb_factory=None):
    """Return an instance of the Flask application.

    Args:
        debug (bool): a flag to activate the debug mode for the app
            (default: False).
        threads (int): number of threads to use
    Return:
        an instance of the Flask application.
    """

    if not bigchaindb_factory:
        bigchaindb_factory = BigchainDB

    app = Flask(__name__)
    app.wsgi_app = StripContentTypeMiddleware(app.wsgi_app)

    CORS(app)

    app.debug = debug

    app.config['bigchain_pool'] = utils.pool(bigchaindb_factory, size=threads)

    add_routes(app)

    return app
Beispiel #18
0
def create_app(**kwargs):
    """Return the OAR API application instance."""
    app = Flask(__name__)
    app.wsgi_app = WSGIProxyFix(app.wsgi_app)
    app.wsgi_app = PrefixMiddleware(app.wsgi_app)
    config.setdefault_config(default_config)
    app.config.update(config)
    db.query_class = APIQuery
    db.query_collection_class = APIQueryCollection
    register_error_handlers(app)
    register_hooks(app)
    register_extensions(app)
    register_blueprints(app)
    register_proxy(app, **kwargs)

    return app
Beispiel #19
0
def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True):
    app = Flask(package_name, instance_relative_config=True)
    app.config.from_object('{}.settings'.format(__package__))
    app.config.from_object(settings_override)

    db.init_app(app)
    mail.init_app(app)
    cache.init_app(app)
    sentry.init_app(app, logging=True, level=logging.ERROR, wrap_wsgi=True)

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, user_datastore,
             register_blueprint=register_security_blueprint,
             register_form=RegisterForm,
             confirm_register_form=ConfirmRegisterForm)

    # noinspection PyUnusedLocal
    @user_registered.connect_via(app)
    def user_registered_sighandler(_app, user, confirm_token):  # pylint: disable=unused-argument,unused-variable
        # Add default user role
        user_datastore.add_role_to_user(user, user_datastore.find_role('user'))
        db.session.add(user)
        db.session.commit()

    register_blueprints(app, package_name, package_path)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    return app
Beispiel #20
0
def create_app(config_name, set_utf=True):
    """App creation factory based on the FLASK_CONFIG env var."""
    if set_utf:
        setdefaultencoding()
    app = Flask(
        __name__,
        template_folder="../templates/",
        static_url_path="/static",
        static_folder="../templates/static/"
    )
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    app.wsgi_app = ProxyFix(app.wsgi_app)

    mount_blueprints(app, config_name)
    add_error_handlers(app)

    if not app.debug:
        app.logger.addHandler(
            get_mail_handler(name=config['default'].APP_NAME,
                             level=logging.ERROR))
    else:
        app.logger.addHandler(get_file_handler())
    return app
def create_app(config={}):
    app = Flask("chassis")
    app.config.from_envvar("FLASK_CONFIG")
    app.config.update(config)

    #External
    sentry.init_app(app)
    api.init_app(app)
    cache.init_app(app)

    #Internal
    db.init_app(app)

    #API Endpoints
    api.add_resource(CatAPI, "/cats/<int:cat_id>")

    with app.app_context():
        db.create_all()

    #Debug tools
    if app.debug:
        DebugToolbarExtension(app)
        if app.config.get("PROFILE", False):
            app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
                                              restrictions=[30],
                                              sort_by=("time", "cumulative"))

    return app
def create_app():
    app = Flask(__name__,
        static_folder=os.path.join(PROJECT_ROOT, 'public'),
        static_url_path='/public')

    app.config.update(os.environ)

    #TODO: read in right hand side from HT config vars
    app.config['SECRET_KEY'] = 'secret'
    app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
    app.config['MONGODB_DB'] = 'flask_security_test'
    app.config['MONGODB_HOST'] = 'localhost'
    app.config['MONGODB_PORT'] = 27017

    app.debug = app.config['X_HT_DEBUG'] == "True"

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, 
        {'/': os.path.join(os.path.dirname(__file__), 'public') })

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    SecuritySetup(app)

    # import & register blueprints here:
    #===================================
    from hero_tmpl.views.security import security
    app.register_blueprint(security)

    from hero_tmpl.views.misc import misc
    app.register_blueprint(misc)

    return app
Beispiel #23
0
def create_app(config_name):                        # app factory, generating our application object
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    db.init_app(app)
    login_manager.init_app(app)
    moment.init_app(app)
    toolbar.init_app(app)

    stats_client.init_app(app)                      # initialize our statsd client, assign it within app
    annotator.init_app(app)                         # initialize our annotator, assign it within app
    app.wsgi_app = statsd_middleware(app)           # initialize our statsd middleware
    # annotator.write(module='app',action='startup',text='application initialized')

    from .main import main as main_blueprint        # blueprints are self contained portions of an application
    app.register_blueprint(main_blueprint, url_prefix='/')

    from .bookmarks import bookmarks as bkm_blueprint
    app.register_blueprint(bkm_blueprint, url_prefix='/bookmarks')

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    @app.after_request                              # sql records are available up until the end of the request
    def after_request(response):                    # hook into 'after request' allowing us to send to statsd
        if app.config['SQLALCHEMY_RECORD_QUERIES']:
            queries = get_debug_queries()
            for query in queries:
                context=query.context.replace(':','_')
                print context
                duration = query.duration * 1000 #convert to ms
                app.stats_client.timing('thermos.queries,context={},path={}'.format(context,request.path),duration)
                print (query.duration)
            return response

    return app
Beispiel #24
0
def create_app():
	app = Flask(__name__)
	app.config.from_pyfile('setting.py')
	register_blueprint(app)
	config_logging(app)
	app.wsgi_app = ProxyFix(app.wsgi_app)
	return app
Beispiel #25
0
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config['SECRET_KEY'] = 'secret'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/profile'

    from tests.test_app.config import Config
    app.config.from_object(Config)

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route('/')
    def index():
        return render_template('index.html', content='Home Page')

    @app.route('/profile')
    @login_required
    def profile():
        twitter = current_app.social.twitter
        twitter.get_api()

        return render_template(
            'profile.html',
            content='Profile Page',
            twitter_conn=twitter.get_connection(),
            google_conn=current_app.social.google.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
            foursquare_conn=current_app.social.foursquare.get_connection())

    return app
Beispiel #26
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 Overholt 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)

    app.config.from_object('milishare.settings')
    app.config.from_pyfile('settings.cfg', silent=True)
    app.config.from_object(settings_override)

    # SQLAlchemy instance.
    db.init_app(app)
    # with app.app_context():
    #     db.create_all()

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #27
0
def create_app(package_name, package_path, settings_override=None):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Overholt 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, instance_path=os.path.dirname(__file__))

    #app.config.from_object('vilya.settings')
    app.config.from_pyfile("app.cfg")
    app.config.from_pyfile("app-dev.cfg", silent=True)
    app.config.from_object(settings_override)

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

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Beispiel #28
0
def make_oauth_wsgi(oauth, next_app, config=None):
    app = Flask(__name__, static_folder=None)
    app.config['PROPAGATE_EXCEPTIONS'] = True

    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('OAUTH_SETTINGS')

    app.next_app = next_app
    oauth.init_app(app)
    app.add_url_rule('/login', endpoint=None, view_func=login)
    app.add_url_rule('/logout', endpoint=None, view_func=logout)
    app.add_url_rule('/login/oauth_callback', endpoint=None, view_func=authorized)
    app.add_url_rule(
        '/',
        endpoint=None, view_func=default_handler,
        methods=['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
    )
    app.add_url_rule(
        '/<path:any>',
        endpoint=None, view_func=default_handler,
        methods=['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],

    )

    auth = get_auth_provider(oauth)
    if not auth._tokengetter:
        auth.tokengetter(get_oauth_token)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app
Beispiel #29
0
def create_app(name='davesite', configuration='Default'):
    """
    Overview: Factory method that is responsible for the following.  Returns the configured Flask app object.
        
            * Reading the configuration.  The configuration is kept in config.py
                
            * Registering the blueprints.  Any blueprints to be added to the application are be added here.     
            
            * Logging: DaveSite uses the built-in python logging module to provide console and file logging.
                       All errors are logged to the console while only warnings and above are logged to the file.
    
    Parameters:
        name:                  package that davesite currently resides under.  
        configuration:         string that points to one of the classes in config.py
        
    Returns: A properly configured Flask application
    """
    app = Flask(name)
    initialize_logging()

    try:
        app.config.from_object('davesite.app.config.{config}'.format(config=configuration))
        initialize_blueprints(app)
    except Exception:
        app.logger.exception("Error while starting app:")
        sys.exit(-1)

    add_file_logging(app.config.get('ERROR_LOG_FILE', 'error.log'), logging.WARN)

    app.wsgi_app = URLPrefixMiddleware(app.wsgi_app, app.config.get('SCRIPT_NAME', '/'))
    return app
Beispiel #30
0
def get_app():
    app = Flask('kardboard')
    app.config.from_object('kardboard.default_settings')
    if os.getenv('KARDBOARD_SETTINGS', None):
        app.config.from_envvar('KARDBOARD_SETTINGS')

    app.secret_key = app.config['SECRET_KEY']

    app.db = PortAwareMongoEngine(app)

    app.jinja_env.add_extension('kardboard.util.Markdown2Extension')
    app.jinja_env.filters['slugify'] = slugify
    app.jinja_env.filters['timesince'] = timesince
    app.jinja_env.filters['jsonencode'] = jsonencode
    app.jinja_env.globals['newrelic_head'] = newrelic_head
    app.jinja_env.globals['newrelic_foot'] = newrelic_foot

    configure_logging(app)

    try:
        from flaskext.exceptional import Exceptional
    except ImportError:
        pass
    exceptional_key = app.config.get('EXCEPTIONAL_API_KEY', '')
    if exceptional_key:
        exceptional = Exceptional(app)
        app._exceptional = exceptional

    app.wsgi_app = FixGunicorn(app.wsgi_app)

    return app