Example #1
0
def create_app(settings_override=None):
    """Returns a :class:`Flask` application instance.
    :param settings_override: a dictionary of settings to override.
    :return: Flask application instance.
    """
    app = Flask(__name__, instance_relative_config=True)
    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3sso.settings")
    app.config.from_object(settings_override)

    # something need init
    db.init_app(app)
    lm.init_app(app)
    Bootstrap(app)

    @lm.user_loader
    def load_user(user_id):
        user = UserProfile.objects.get(id=user_id)
        return user

    app.register_blueprint(bp_main)
    app.register_blueprint(bp_sso)
    app.register_blueprint(bp_api)
    app.register_blueprint(bp_api_1_0)

    for e in [500, 404]:
        app.errorhandler(e)(handle_error)

    return app
Example #2
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.secret_key = 'this is a secret'
    app.json_encoder = Jsonifier

    app.file_root = os.path.abspath(os.path.dirname(__file__))

    app.before_request(before_request)
    app.after_request(after_request)
    app.context_processor(context_processor)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

    db.init_app(app)
    with app.app_context():
        init_all()
    app.register_blueprint(admin_app, url_prefix='/admin')
    app.register_blueprint(campaign_app, url_prefix='/')
    app.register_blueprint(character_app, url_prefix='/character')
    app.register_blueprint(dm_app, url_prefix='/dm')
    app.register_blueprint(chat_app, url_prefix='/chat')
    app.register_blueprint(items_app, url_prefix='/item-type')
    app.register_blueprint(knowledge_app, url_prefix='/knowledge')

    return app
Example #3
0
File: app.py Project: cryptk/opsy
def create_app(config_file):
    app = Flask(__name__)
    load_config(app, config_file)
    create_logging(app)
    configure_extensions(app)
    app.jobs = []  # FIXME: Need to handle scheduled jobs better.
    app.needs_catalog = {'core': needs}
    app.register_blueprint(core_main)
    app.register_blueprint(core_api)
    for plugin in load_plugins(app):
        validate_config(app, plugin=plugin)
        app.needs_catalog[plugin.name] = plugin.needs
        plugin.register_blueprints(app)
    app.json_encoder = OpsyJSONEncoder
    app.plugin_links = [{
        'name': 'About',
        'id': 'about',
        'content': 'core_main.about',
        'get_vars': None,
        'type': 'link'
    }]

    @app.before_first_request
    def load_plugin_links():  # pylint: disable=unused-variable
        for plugin in load_plugins(app):
            plugin.register_link_structure(app)

    @app.context_processor
    def inject_links():  # pylint: disable=unused-variable
        return dict(link_structures=app.plugin_links)
    return app
Example #4
0
def create_base_app(config):
    """Init configuration and extensions"""
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)

    app._logger = init_logger(syslogtag=app.config['LOGGER_SYSLOGTAG'],
                              logger_name=app.config['LOGGER_NAME'])

    db.init_app(app)
    bcrypt.init_app(app)

    if app.config['DEBUG']:
        admin_extension.init_app(app)
        debug_toolbar.init_app(app)

    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous
    # Change these views to fit your app
    login_manager.login_view = "auth.login"
    login_manager.refresh_view = "auth.login"
    login_manager.login_message = "You do not have access to that page."
    login_manager.user_loader(load_user)

    app.json_encoder = CustomJSONEncoder

    return app
Example #5
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.json_encoder = CustomJSONEncoder
    config[config_name].init_app(app)

    db.init_app(app)
    csrf.init_app(app)
    babel.init_app(app)
    mail.init_app(app)
    breadcrumbs.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)

    if not app.debug and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

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

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    return app
Example #6
0
def create_app():
    """Create an application instance."""
    cfg = os.path.join(os.getcwd(), 'config.py') if os.path.exists('config.py') else os.path.join(os.getcwd(), 'mopa/config.py')

    app = Flask(__name__)
    app.json_encoder = CustomJSONEncoder
    app.config['JSON_PRETTYPRINT_REGULAR'] = False
    app.config.from_pyfile(cfg)
    setup_logging(app)

    # initialize extensions
    db.init_app(app)
    reggie.init_app(app)
    # cors.init_app(app, resources={r"/api/*": {"origins": "*"}})

    # One line of code to cut our Flask page load times by 60%
    # https://blog.socratic.org/the-one-weird-trick-that-cut-our-flask-page-load-time-by-70-87145335f679#.8r14wvy5w
    app.jinja_env.cache = {}

    # register blueprints
    from .views import bp as api_blueprint
    app.register_blueprint(api_blueprint)

    from .tasks import bp as tasks_blueprint
    app.register_blueprint(tasks_blueprint, url_prefix='/tasks')

    return app
Example #7
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.json_encoder = JSONEncoder
    config[config_name].init_app(app)

    babel = Babel(app)

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

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

    from .field_storage import field_storage as field_storage_blueprint
    app.register_blueprint(field_storage_blueprint)

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

    from .unis import unis as unis_blueprint
    app.register_blueprint(unis_blueprint)

    return app
def create_base_app(config):
    """Init configuration and extensions"""
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)

    file_handler = SysLogHandler()
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

    db.init_app(app)
    bcrypt.init_app(app)

    if app.config['DEBUG']:
        admin_extension.init_app(app)
        debug_toolbar.init_app(app)

    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous
    # Change these views to fit your app
    login_manager.login_view = "auth.login"
    login_manager.refresh_view = "auth.login"
    login_manager.login_message = "You do not have access to that page."
    login_manager.user_loader(load_user)

    app.json_encoder = CustomJSONEncoder

    return app
Example #9
0
def create_app(config_override=None, environment=None):
    app = Flask(__name__)
    app.config['ENVIRONMENT'] = environment
    config.init_app(app)
    app.config.update(config_override or {})

    severity.init_app(app)
    key_helper.init_app(app)

    cors.init_app(app)
    compress.init_app(app)
    handlers.register(app)

    db.init_db(app)
    qb.init_app(app)
    sentry.init_app(app)

    from alerta.utils.format import CustomJSONEncoder
    app.json_encoder = CustomJSONEncoder

    from alerta.views import api
    app.register_blueprint(api)

    from alerta.webhooks import webhooks
    app.register_blueprint(webhooks)

    from alerta.auth import auth
    app.register_blueprint(auth)

    from alerta.management import mgmt
    app.register_blueprint(mgmt)

    plugins.register(app)

    return app
Example #10
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 Tcc3Portal 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`.
    :return: Flask application instance.
    """
    app = Flask(package_name, instance_relative_config=True)

    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3portal.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    # something need init
    # security.init_app(app, None, register_blueprint=register_security_blueprint)
    db.init_app(app)
    bootstrap.init_app(app)
    lm.init_app(app)
    babel.init_app(app)
    sso_client.init_app(app, lm)
    TccFrontend(app)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Example #11
0
def create_api_app(config=None):
    app = Flask(__name__)

    if config:
        app.config.from_pyfile(config)

    app.config['JSONSCHEMA_DIR'] = os.path.abspath('doorbot/views/api/schemas')

    app.url_map.strict_slashes = False

    jsonschema.init_app(app)
    db.init_app(app)

    from .container import container
    container.init_app(app)

    from .views.api import (
        account, auth, devices, doors, integrations, notifications, people
    )
    from .views.api.lib.json_serializer import ApiJsonEncoder

    app.json_encoder = ApiJsonEncoder
    app.register_blueprint(auth)
    app.register_blueprint(account)
    app.register_blueprint(devices)
    app.register_blueprint(doors)
    app.register_blueprint(integrations)
    app.register_blueprint(notifications)
    app.register_blueprint(people)

    return app
Example #12
0
 def test_custom_json_encoder(self):
     from datetime import datetime
     from flask.json import JSONEncoder
     class JsonEncoder(JSONEncoder):
         def default(self, obj):
             if hasattr(obj, '__json__'):
                 return obj.__json__()
             if isinstance(obj, datetime):
                 return obj.isoformat()
             return super(JsonEncoder, self).default(obj)
     class Custom:
         def __init__(self, custom):
             self.custom = custom
         def __json__(self):
             return dict(custom=self.custom)
     date = datetime(2014,5,26,23,59,59)
     class DateResource(flask_restful.Resource):
         def get(self):
             return Custom(date)
     app = Flask(__name__)
     app.json_encoder = JsonEncoder
     api = flask_restful.Api(app)
     api.add_resource(DateResource, '/date')
     client = app.test_client()
     resp = client.get('/date')
     self.assertEquals(resp.data.decode(), '{"custom": "2014-05-26T23:59:59"}')
Example #13
0
def create_app(config):

    """A factory that returns an application object from the passed config.

    The factory accepts further configuration from ENV variables. Some simple
    checks for core configuration settings are made to raise errors early
    if vital information is missing.

    """

    import os
    from flask import Flask
    from flask.ext.babel import Babel
    from flask.ext.cors import CORS
    from flask.ext.markdown import Markdown
#    from flask.ext.assets import Environment, Bundle
    from .components import api, pages
    from .components.commons import context_processors, encoders

    app_label = 'web'

    # Get the static and template folder for the passed theme
    static_folder = os.path.join('theme', 'static')
    template_folder = os.path.join('theme', 'templates')

    # Construct app and service objects
    app = Flask(app_label, template_folder=template_folder,
                static_folder=static_folder, static_url_path='/static')
    trans = Babel()
    cors = CORS(resources=r'/api/*', allow_headers='Content-Type')
#    assets = Environment()

    # Configure the app with defaults
    app.config.from_object(config)

    # Set app core services
    trans.init_app(app)
    cors.init_app(app)
#    assets.init_app(app)
    Markdown(app)

    # Register routable components
    app.register_blueprint(api.blueprint)
    app.register_blueprint(pages.blueprint)

    # Set additional jinja2 extensions
    app.jinja_env.add_extension('jinja2.ext.do')

    # Set custom context processors
    app.context_processor(context_processors.inject_app_data)

    # Set custom encoders
    app.json_encoder = encoders.JSONEncoder

    # Register webassets bundles
#    sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css')
#    assets.register('sass', sass)

    return app
Example #14
0
def create_app():
  from views.index import index_view
  from views.api import api_view

  app = Flask(__name__)
  app.register_blueprint(api_view)
  app.register_blueprint(index_view)
  app.json_encoder = SetJSONEncoder
  return app
Example #15
0
    def create_app(self):
        app = Flask(__name__)
        app.json_encoder = _JSONEncoder
        app.secret_key = "secret"

        @app.route("/", methods=("GET", "POST"))
        def index():

            form = MyForm()
            if form.validate_on_submit():
                name = form.name.data.upper()
            else:
                name = ''

            return render_template("index.html",
                                   form=form,
                                   name=name)

        @app.route("/simple/", methods=("POST",))
        def simple():
            form = SimpleForm()
            form.validate()
            assert form.csrf_enabled
            assert not form.validate()
            return "OK"

        @app.route("/two_forms/", methods=("POST",))
        def two_forms():
            form = SimpleForm()
            assert form.csrf_enabled
            assert form.validate()
            assert form.validate()
            form2 = SimpleForm()
            assert form2.csrf_enabled
            assert form2.validate()
            return "OK"

        @app.route("/hidden/")
        def hidden():

            form = HiddenFieldsForm()
            return render_template("hidden.html", form=form)

        @app.route("/ajax/", methods=("POST",))
        def ajax_submit():
            form = MyForm()
            if form.validate_on_submit():
                return jsonify(name=form.name.data,
                               success=True,
                               errors=None)

            return jsonify(name=None,
                           errors=form.errors,
                           success=False)

        return app
Example #16
0
def init_app():
    """Init flask app"""

    app = Flask(__name__)
    app.config.from_object(base_config)
    # Production or local config
    app.config.from_envvar('QFOOD_CONFIG', silent = True)
    # set json encoder capable serializing MongoDB ObjectId
    app.json_encoder = JSONEncoder

    return app
 def setUp(self):
     app = Flask(__name__)
     app.session_interface = CheckerSessionInterface()
     app.json_encoder = CustomJSONEncoder
     app.config["SECRET_KEY"] = "test"
     app.add_url_rule("/<step>", view_func=TestWizard.as_view("wizard"))
     app.add_url_rule(
         "/session-expired", endpoint="base.session_expired", view_func=lambda request: "Session expired"
     )
     self.client = app.test_client()
     with self.client.session_transaction() as sess:
         sess.checker["foo"] = "bar"
Example #18
0
def create_app():
    flask_app = Flask(__name__)

    # load site settings from the database
    setup_settings(flask_app)

    # environment-aware configuration
    setup_config(flask_app)

    # custom NDB model serializer
    flask_app.json_encoder = NDBModelJSONEncoder

    return flask_app
Example #19
0
 def test_jsonencoder(self):
     from api import api
     app = Flask(__name__)
     app.json_encoder = api.CustomJSONEncoder
     @app.route('/test_json_basic')
     def json_basic():
         return jsonify(result='test')
     now = datetime.datetime.now()
     @app.route('/test_json_datetime')
     def json_datetime():
         return jsonify(result=now)
     @app.route('/test_json_iter')
     def json_iter():
         class Counter:
             def __init__(self, value):
                 self._value = value
                 self._current = 0
             def __iter__(self):
                 return self
             def __next__(self):
                 if self._current > self._value:
                     raise StopIteration
                 else:
                     self._current += 1
                     return self._current - 1
             def next(self):
                 return self.__next__()
         return jsonify(result=Counter(5))
     @app.route('/test_json_error')
     def json_error():
         class NewObject:
             def __init__(self, value):
                 self._value = value
         return jsonify(result=NewObject(5))
     test_app = app.test_client()
     rv = test_app.get('/test_json_basic')
     assert rv.status_code == 200
     res = json.loads(rv.data.decode('utf-8'))
     assert res == {'result': 'test'}
     rv = test_app.get('/test_json_datetime')
     assert rv.status_code == 200
     res = json.loads(rv.data.decode('utf-8'))
     assert res == {'result': now.strftime(api.time_format)}
     rv = test_app.get('/test_json_iter')
     assert rv.status_code == 200
     res = json.loads(rv.data.decode('utf-8'))
     assert res == {'result': [0, 1, 2, 3, 4, 5]}
     rv = test_app.get('/test_json_error')
     assert rv.status_code == 500
Example #20
0
def create_app(config_from_object=None, config_from_env=None):
  """A factory function to produce a Flask application instance

  This will create the one true application, in a flexible and extensible way.
  The app is being created via a factory function in order to facilitate custom
  or manual configurations.  In this fashion, the app could be configured
  automatically by the Flask-Script file ``manage.py`` during development using
  an environment variable on a local workstation prescribing a
  ``DevelopmentConfig``, while on the production machine, it will resolve to a
  ``ProductionConfig``, or manually specified in the tests directory during set-
  up as ``TestingConfig`` as defined in the :mod:`foodtruck.config` module.

  The app will register the :mod:`foodtruck.backend` module at the endpoint
  specified by``API_ENDPOINT`` using a Flask blueprint in a self-contained
  backend sub-package, demonstrating the flexibility Flask provides.

  Args:
    config_from_object (str, optional): A string representing the name of an
      object to import
    config_from_env  (str, optional): A string representing the name of the
      environment variable to pull the name of the object to import

  Note:
    While both arguments are optional, at least **one** is mandatory.
    Otherwise, where will we get our configs??
  """
  setup_log()
  log = logging.getLogger(__name__)

  app = Flask(__name__)

  if config_from_env:
    app.config.from_object(os.environ[config_from_env])
  # While the ENVIRONMENT configures first, the config object can be used to
  # merge and overwrite settings, providing additional flexibility
  if config_from_object:
    app.config.from_object(config_from_object)

  # We'll be mounting our API right on this endpoint here:
  app.register_blueprint(api_blueprint,
                         url_prefix='/'+app.config['API_ENDPOINT'])
  app.register_blueprint(frontend_blueprint)

  # Register our JSON encoder too
  app.json_encoder = UltraJSONEncoder

  db.init_app(app)

  return app
def create_app(_config='development'):
    app = Flask(__name__)

    CORS(app)

    app.config.from_object(config[_config])
    app.json_encoder = MyJSONEncoder

    from app.inventory import views
    from app.cart import views
    from app import views

    app.register_blueprint(api)

    return app
Example #22
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.json_encoder = AlchemyEncoder

    app.config.from_object(Config)

    DebugToolbarExtension(app)

    init_flask_config(app)
    init_extensions(app)
    init_session(app)
    init_blueprints(app)
    init_state(app)

    return app
def create_app(config_name):
    application = Flask(__name__)
    application.config['DM_ENVIRONMENT'] = config_name

    init_app(
        application,
        configs[config_name],
        db=db,
        search_api_client=search_api_client
    )

    if not application.config['DM_API_AUTH_TOKENS']:
        raise Exception("No DM_API_AUTH_TOKENS provided")

    # FIXME: The service broker adds a 'reconnect' parameter that's rejected by Postgres and
    # doesn't seem to be in the Postgres documentation anyway.  We need to patch the broker to fix
    # the username stability issue anyway.
    import os
    if 'DATABASE_URL' in os.environ:
        application.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'].replace('reconnect=true', '')

    url_prefix = application.config['URL_PREFIX']
    url_prefix_v2 = application.config['URL_PREFIX_V2']
    from .main import main as main_blueprint
    application.register_blueprint(main_blueprint, url_prefix=url_prefix)
    from .status import status as status_blueprint
    application.register_blueprint(status_blueprint, url_prefix=url_prefix)
    from .api import api as api_blueprint
    application.register_blueprint(api_blueprint, url_prefix=url_prefix_v2)
    from .admin import blueprint as admin_blueprint
    application.register_blueprint(admin_blueprint.admin)

    application.json_encoder = CustomEncoder

    # maximum POST request length http://flask.pocoo.org/docs/0.12/patterns/fileuploads/#improving-uploads
    application.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024  # 32 megabytes

    swag.init_app(application)

    if application.config['DEBUG']:
        # enable raise to raise exception on ORM misconfigured queries
        # application.config['NPLUSONE_RAISE'] = True
        application.config['NPLUSONE_LOGGER'] = logging.getLogger('app.nplusone')
        application.config['NPLUSONE_LOG_LEVEL'] = logging.ERROR
        NPlusOne(application)
        application.wsgi_app = SQLTapMiddleware(application.wsgi_app)

    return application
Example #24
0
def create_app(config):
    """
    Application Factories - http://flask.pocoo.org/docs/patterns/appfactories/
    :param config: Path to config.py file.
    """

    app = Flask(__name__)
    app.config.from_pyfile(config)
    db.init_app(app)
    api = Api(app)

    from application.json_encoder import AlchemyEncoder
    app.json_encoder = AlchemyEncoder

    # Register middlewares here
    from application.middlewares import require_login, apply_cors_headers
    app.before_request(require_login)
    app.after_request(apply_cors_headers)

    # Register blueprints here
    from application.views import bp as bp_auth
    app.register_blueprint(bp_auth)

    from application.views import UserList, UserResource, GroupList, SubjectList, SubjectSignupList, \
        SubjectSignupResource, TermSignupAction, SettingList
    
    api.add_resource(UserList, '/api/users')
    api.add_resource(UserResource, '/api/users/<int:id>')
    api.add_resource(GroupList, '/api/groups')
    api.add_resource(SubjectList, '/api/subjects')
    api.add_resource(SubjectSignupList, '/api/subjects_signup')
    api.add_resource(SubjectSignupResource, '/api/subjects_signup/<int:subject_id>')
    api.add_resource(TermSignupAction, '/api/terms/signup')
    api.add_resource(SettingList, '/api/settings')

    # Admin panel
    from application.models import User, Group, Subject, Term, TermSignup, Setting
    from application.admin import UserAdminView, SubjectAdminView, TermAdminView, TermSignupAdminView, SettingAdminView

    admin = Admin(app)
    admin.add_view(UserAdminView(User, db.session))
    admin.add_view(ModelView(Group, db.session))
    admin.add_view(SubjectAdminView(Subject, db.session))
    admin.add_view(TermAdminView(Term, db.session))
    admin.add_view(TermSignupAdminView(TermSignup, db.session))
    admin.add_view(SettingAdminView(Setting, db.session))

    return app
Example #25
0
def create_app(testing=False):
    app = Flask(__name__)

    try:
        app.config.from_object('config')
    except:
        app.config.from_object('configdist')
    if testing:
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False

    app.json_encoder = ExtensibleJSONEncoder
    app.secret_key = app.config['SECRET_KEY']
    app.register_blueprint(user_bp)

    csrf = CsrfProtect()
    csrf.init_app(app)

    # Initialize login manager
    login_manager.init_app(app)

    # Assets bundles: js, jsx, css
    env = Environment(app)
    root = os.path.dirname(os.path.abspath(__file__)) + '/../'
    env.load_path = [
        root + 'node_modules',
        root + 'client/style'
    ]
    env.register('css', css)

    @app.teardown_appcontext
    def shutdown_session(response):
        database.session.remove()

    @app.route('/')
    @app.route('/<path:path>')
    def index(path=None):
        """Main route for the single page app"""
        data = dict(
            user=anonymous_user_data,
            alerts=[]
        )
        if current_user.is_authenticated():
            data['user'] = current_user
        return render_template('index.html', app_data=dumps(data))

    return app
Example #26
0
def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'THIS IS JUST A TEST WEBPAGE !'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:R0boo@Sip$@127.0.0.1/maizi'
    app.config['BABEL_DEFAULT_LOCALE'] = 'en'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    from flask.json import JSONEncoder

    class CustomJSONEncoder(JSONEncoder):
        """This class adds support for lazy translation texts to Flask's
        JSON encoder. This is necessary when flashing translated texts."""

        def default(self, obj):
            from speaklater import is_lazy_string
            if is_lazy_string(obj):
                try:
                    return unicode(obj)  # python 2
                except NameError:
                    return str(obj)  # python 3
            return super(CustomJSONEncoder, self).default(obj)

    app.json_encoder = CustomJSONEncoder

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
    Gravatar(app, size=64)
    babel.init_app(app)

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

    app.permanent_session_lifetime = timedelta(minutes=5)

    @app.template_test('current_link')
    def is_current_link(link):
        return link == request.path

    @babel.localeselector
    def get_locale():
        return current_user.locale

    return app
Example #27
0
def create_app(config_object=ProdConfig):
    """An application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

  :param config_object: The configuration object to use.
  """
    app = Flask(__name__)
    app.config.from_object(config_object)
    app.json_encoder = JSONEncoder
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)

    if app.config["ADMIN_ENABLED"]:
        register_admin_interface(app)

    return app
Example #28
0
def create_app(config_override: Mapping = None) -> Flask:
    """Create the flask app for the debug server.

    Parameters:
        config_override:
            Dict containing custom configuration to apply after loading the
            normal config. Useful for testing.
    """
    config_override = {} if config_override is None else config_override
    # TODO: Rename app, no longer used only for debugging
    app = Flask('stuffrdebugserver',
                instance_relative_config=True,
                static_url_path='',
                template_folder='static')
    app.config.from_object('config.default')
    app.config.from_envvar('STUFFR_SETTINGS')
    app.config.from_mapping(config_override)
    app.json_encoder = StuffrJSONEncoder
    logger.set_logger(app.logger)

    db.init_app(app)
    security = Security(app, user_store, confirm_register_form=StuffrRegisterForm)
    security.unauthorized_handler(api_unauthenticated_handler)
    Mail(app)

    # In debug mode Swagger documentation is served at root
    if not app.config['DEBUG']:
        def api_root_view():
            """Provide a link to API documentation if root accessed."""
            return error_response(
                'TODO: Link to documentation here', HTTPStatus.NOT_FOUND)
        blueprint_api.add_url_rule('/', 'apiindex', api_root_view)

    app.register_blueprint(blueprint_simple, url_prefix='/simple')
    app.register_blueprint(blueprint_api, url_prefix='/api')

    def default404(e):
        """Default handler for 404."""
        # TODO: Conditional JSON/HTML response (for simple mode)
        return error_response(e.description, HTTPStatus.NOT_FOUND)
    app.register_error_handler(HTTPStatus.NOT_FOUND, default404)

    # TODO: Make friendlier error message (40x or 50x?)
    app.add_url_rule('/', 'index', lambda: "You probably shouldn't be here")

    return app
Example #29
0
def create_app(config=None):
    app = Flask(__name__)

    app.config.from_object('wedding_site.default_config')
    if 'WEDDING_SITE_CONFIG' in os.environ:
        app.config.from_envvar('WEDDING_SITE_CONFIG')
    if config:
        app.config.from_object(config)

    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.json_encoder = CustomJSONEncoder
    app.jinja_env.globals['momentjs'] = momentjs

    init_extensions(app)
    init_views(app)

    return app
Example #30
0
def create_app(config=config.Local):
    app = Flask(__name__)
    app.config.from_object(config)
    app.json_encoder = CustomJSONEncoder
    db.init_app(app)


    register_blueprints(app)

    @app.before_request
    def set_logging_context():
        """
        Extract the logging context from the request and add it to the kloggyr factory.
        """
        # TODO add these for anti_charity. Standard analytics logging requirements are specified in
        #   the 'Standard Analytics Kloggyr Event Names' document on Confluence.
        #   https://kyruus.jira.com/wiki/display/ANL/Standard+Analytics+Kloggyr+Events

    @app.context_processor
    def get_landing_page_js_url():
        if app.config.get('LOCAL_JS'):
            url = 'static/js/anticharity_landing_page.js'
        else:
            url = 'https://s3-us-west-2.amazonaws.com/anticharity/js/manual_upload/anticharity_landing_page.min.js'
        return {'landing_page_js_url': url}

    @app.context_processor
    def get_app_js_url():
        if app.config.get('LOCAL_JS'):
            url = 'static/js/anti_charity.js'
        else:
            url = 'https://s3-us-west-2.amazonaws.com/anticharity/js/manual_upload/anti_charity.min.js'
        return {'app_js_url': url}


    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        """A handler for any endpoint that raises an InvalidUsage exception"""
        return jsonify(error.to_dict()), error.status_code

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db.session.remove()

    return app