Beispiel #1
0
def make_wsgi_app(settings_filepath=None, testing=False):
    with start_action(action_type='morepath_scan'):
        morepath.autoscan()
        morepath.scan(ekklesia_portal)

    if testing:
        log_message(
            message_type="testing",
            msg="running in testing mode, not loading any config from file")
    else:
        with start_action(action_type='settings'):
            settings = get_app_settings(settings_filepath)
            App._loaded_settings = settings
            App.init_settings(settings)

    with start_action(action_type='make_app'):
        App.commit()
        app = App()

    database.configure_sqlalchemy(app.settings.database, testing)
    app.babel_init()
    app.babel.localeselector(get_locale)
    log_message(message_type="environment",
                env=dict(os.environ),
                encoding=locale.getpreferredencoding(),
                default_locale=locale.getdefaultlocale())
    return app
Beispiel #2
0
def run():   # pragma: no cover
    engine = sqlalchemy.create_engine('sqlite:///morepath_sqlalchemy.db')
    Session.configure(bind=engine)
    Base.metadata.create_all(engine)

    morepath.autoscan()
    morepath.run(App())
def app(test_app_class):
    morepath.autoscan()
    test_app_class.init_settings(SETTINGS)
    test_app_class.commit()

    app = test_app_class()
    return app
Beispiel #4
0
def wsgi_factory():  # pragma: no cover
    morepath.autoscan()

    App.commit()
    setup_db()

    return App()
Beispiel #5
0
def wsgi_factory():   # pragma: no cover
    morepath.autoscan()

    App.commit()
    setup_db()

    return App()
Beispiel #6
0
def get_client(app):
    class Tapp(app):
        pass
    morepath.autoscan()
    morepath.commit(Tapp)
    c = Client(Tapp())
    return c
Beispiel #7
0
def create_app(app,
               settings,
               sqlalchemy_session=Session,
               sqlalchemy_bases=None):
    sqlalchemy_bases = sqlalchemy_bases or []
    register_session(sqlalchemy_session)
    # initialize SQLAlchemy
    if 'sqlalchemy' in settings:
        cwd = os.getcwd()
        engine = sqlalchemy.create_engine(settings['sqlalchemy']['dburi'] %
                                          {'here': cwd})
        sqlalchemy_session.configure(bind=engine)

    # initialize app
    app.init_settings(settings)
    morepath.commit(app)
    morepath.autoscan()
    app.commit()
    application = app()

    # create tables
    if 'sqlalchemy' in settings:
        for base in sqlalchemy_bases:
            base.metadata.create_all(engine)

    return application
Beispiel #8
0
def wsgi_factory():  # pragma: no cover
    morepath.autoscan()

    if os.getenv("RUN_ENV") == "production":
        ProductionApp.commit()
        app = ProductionApp()
    elif os.getenv("RUN_ENV") == "test":
        TestApp.commit()
        app = TestApp()
    else:
        App.commit()
        app = App()

    index = FileApp("build/index.html")
    static = DirectoryApp("build", index_page=None)

    setup_db(app)

    @webob.dec.wsgify
    def morepath_with_static_absorb(request):
        popped = request.path_info_pop()
        if popped == "api":
            return request.get_response(app)
        elif popped == "static":
            return request.get_response(static)
        else:
            return request.get_response(index)

    return morepath_with_static_absorb
Beispiel #9
0
def run():  # pragma: no cover
    engine = sqlalchemy.create_engine("sqlite:///morepath_sqlalchemy.db")
    Session.configure(bind=engine)
    Base.metadata.create_all(engine)

    morepath.autoscan()
    morepath.run(App())
Beispiel #10
0
def assert_explicit_permissions(module, app_class):
    morepath.autoscan()
    app_class.commit()

    for action, fn in dectate.Query('view')(app_class):
        if fn.__module__.startswith('onegov'):
            assert action.permission is not None, (
                f'{fn.__module__}.{fn.__name__} has no permission')
Beispiel #11
0
def query_tool():
    """Usa dectate.query_tool() para consultar las rutas de la API."""
    morepath.autoscan()
    # Cargamos la configuración de la aplicación
    with open('settings.json') as config:
        settings_dict = json.load(config)
    App.init_settings(settings_dict)
    morepath.commit(App)
    dectate.query_tool(App.commit())
Beispiel #12
0
def assert_explicit_permissions(module, app_class):
    morepath.autoscan()
    app_class.commit()

    for action, fn in dectate.Query('view')(app_class):
        if fn.__module__.startswith('onegov'):
            assert action.permission is not None, (
                f'{fn.__module__}.{fn.__name__} has no permission'
            )
Beispiel #13
0
def app(test_app_class):
    custom_settings = {**BABEL_SETTINGS, 'configure_jinja': False}
    morepath.autoscan()
    test_app_class.init_settings(dict(babel_i18n=custom_settings))
    test_app_class.commit()

    app = test_app_class()
    app.babel_init()
    return app
Beispiel #14
0
def get_client(app, config='settings.yml'):
    if isinstance(config, str):
        with open(os.path.join(os.path.dirname(__file__), config)) as f:
            settings = yaml.load(f) or {}
    else:
        settings = config

    morepath.autoscan()
    app.init_settings(settings)
    morepath.commit(app)
    c = Client(app())
    return c
Beispiel #15
0
def initdb():
    click.echo('Initialize database...')
    morepath.autoscan()
    app = App()
    app.commit()
    # create database
    dbsession = app.find_service(name='dbsession')
    Base.metadata.create_all(dbsession.bind)
    # add users
    users = app.find_service(name='users')
    with transaction.manager:
        for user in USERS:
            users.add(**user)
        transaction.commit()
Beispiel #16
0
def run():
    morepath.autoscan()

    with open('settings/default.yaml') as defaults:
        defaults_dict = yaml.load(defaults)

    App.init_settings(defaults_dict)
    App.commit()
    app = App()
    setup_db(app)

    run_simple(app.settings.run.host,
               app.settings.run.port,
               DebuggedApplication(app, evalex=True),
               use_reloader=True)
Beispiel #17
0
def make_wsgi_app(settings_filepath=None, testing=False):
    with start_action(action_type='morepath_scan'):
        morepath.autoscan()
        morepath.scan(ekklesia_voting)

    with start_action(action_type='settings'):
        settings = get_app_settings(settings_filepath)
        App.init_settings(settings)

    with start_action(action_type='make_app'):
        App.commit()
        app = App()

    database.configure_sqlalchemy(app.settings.database, testing)
    app.babel_init()
    app.babel.localeselector(get_locale)
    return app
def run():   # pragma: no cover
    morepath.autoscan()

    index = FileApp('static/index.html')
    static = DirectoryApp('static')
    app = App()

    @webob.dec.wsgify
    def morepath_with_static_absorb(request):
        popped = request.path_info_pop()
        if popped == 'api':
            return request.get_response(app)
        elif popped == 'static':
            return request.get_response(static)
        else:
            return request.get_response(index)

    morepath.run(morepath_with_static_absorb)
Beispiel #19
0
def run():  # pragma: no cover
    morepath.autoscan()

    index = FileApp('static/index.html')
    static = DirectoryApp('static')
    app = App()

    @webob.dec.wsgify
    def morepath_with_static_absorb(request):
        popped = request.path_info_pop()
        if popped == 'api':
            return request.get_response(app)
        elif popped == 'static':
            return request.get_response(static)
        else:
            return request.get_response(index)

    morepath.run(morepath_with_static_absorb)
Beispiel #20
0
def run():  # pragma: no cover
    # This is super-hacky, but whatever - this was always intended to be a
    # temporary solution anyway
    if len(argv) > 1:
        # We clean the config filename off so as not to confuse morepath
        config_settings(argv.pop())
    else:
        print('Need a list name (should be in form-data/)')
        exit(1)

    engine = sqlalchemy.create_engine('sqlite:///sf_app.db')
    Session.configure(bind=engine)
    Base.metadata.create_all(engine)

    morepath.autoscan()

    # Not entirely clear if I need this
    morepath.commit(App)
    morepath.run(App())
Beispiel #21
0
def run():   # pragma: no cover
    morepath.autoscan()

    index = FileApp('static/index.html')
    static = DirectoryApp('static')
    app = App()

    @webob.dec.wsgify
    def morepath_with_static(request):
        if request.path_info_peek() == '':
            return request.get_response(index)

        popped = request.path_info_pop()
        if popped == 'api':
            return request.get_response(app)
        elif popped == 'static':
            return request.get_response(static)

        raise HTTPNotFound()

    morepath.run(morepath_with_static)
Beispiel #22
0
def run():
    directive_logger = logging.getLogger('morepath.directive')
    directive_logger.addHandler(logging.StreamHandler())
    directive_logger.setLevel(logging.DEBUG)

    with open('settings.yml') as config:
        settings_dict = yaml.load(config)

    App.init_settings(settings_dict)

    morepath.autoscan()
    morepath.commit(App)
    app = App()

    setup_db(app)

    if os.getenv('RUN_ENV') == 'dev':
        morepath.run(app, host='0.0.0.0', port='80')
    else:
        waitress_logger = logging.getLogger('waitress')
        waitress_logger.setLevel(logging.INFO)
        waitress.serve(app, listen="*:80")
Beispiel #23
0
def instance_app():
    """Crea una instancia de la aplicación"""

    morepath.autoscan()

    # Lo siguiente prepara el logger de pony.orm para que emita a un
    # fichero todas las sentencias SQL que va enviando a la base de datos
    # pony.orm.sql_debug(True)
    # logger = logging.getLogger("pony.orm.sql")
    # logger.setLevel(logging.INFO)
    # channel = logging.FileHandler("/tmp/sql_commands.log")
    # channel.setLevel(logging.INFO)
    # logger.addHandler(channel)

    # Hay que añadirle un handler a logging.root porque (según he visto
    # en el código de pony) sql_log() comprueba que haya uno, y si no lo
    # hay emite las cosas por la salida estándar haciendo caso omiso de la
    # configuración de log. Pero como no me interesa que el logger raiz
    # haga nada, le asigno el handler nulo
    # logging.root.addHandler(logging.NullHandler())

    env = os.getenv("RUN_ENV", "default")
    filename = "settings/{}.yaml".format(env)
    if not os.path.isfile(filename):
        filename = "settings/default.yaml"

    print("Usando configuración {}".format(filename))
    # Cargamos la configuración de la aplicación
    with open(filename) as config:
        settings_dict = yaml.load(config)
    App.init_settings(settings_dict)
    # morepath.commit(App)
    App.commit()

    app = App()

    setup_redis(app)
    setup_db(app)
    return app
Beispiel #24
0
def create_baseapp(app, settings, scan=True, **kwargs):

    s = copy.deepcopy(default_settings)
    for k in settings.keys():
        if k in s.keys():
            for j, v in settings[k].items():
                s[k][j] = v
        else:
            s[k] = settings[k]

    settings = s

    # initialize app

    if scan:
        morepath.autoscan()
        for scanmodpath in (settings['morpfw']['scan'] or []):
            scanmod = importlib.import_module(scanmodpath)
            morepath.scan(package=scanmod)

    app_settings = settings['application']

    authnpolicy_settings = app_settings['authn_policy_settings']
    authnpol_mod, authnpol_clsname = (
        app_settings['authn_policy'].strip().split(':'))

    authnpolicy = getattr(importlib.import_module(authnpol_mod),
                          authnpol_clsname)(authnpolicy_settings)

    get_identity_policy = authnpolicy.get_identity_policy
    verify_identity = authnpolicy.verify_identity

    mounted_apps = app_settings['mounted_apps']
    if getattr(authnpolicy, 'app_cls', None):
        mounted_apps.append({
            'app_cls':
            authnpolicy.app_cls,
            'authn_policy':
            app_settings['authn_policy'],
            'authn_policy_settings':
            app_settings['authn_policy_settings']
        })
    for iapp in mounted_apps:
        if 'app_cls' in iapp.keys():
            iapp_cls = iapp['app_cls']
        else:
            iapp_path = iapp['app']
            iapp_mod, iapp_clsname = iapp_path.strip().split(':')
            iapp_cls = getattr(importlib.import_module(iapp_mod), iapp_clsname)

        if iapp.get('authn_policy', None):
            iapp_authnpolicy_settings = iapp.get('authn_policy_settings', {})
            iapp_authnpol_mod, iapp_authnpol_clsname = (
                iapp['authn_policy'].strip().split(':'))
            iapp_authnpolicy = getattr(
                importlib.import_module(iapp_authnpol_mod),
                iapp_authnpol_clsname)(iapp_authnpolicy_settings)
            iapp_get_identity_policy = iapp_authnpolicy.get_identity_policy
            iapp_verify_identity = iapp_authnpolicy.verify_identity
            iapp_cls.identity_policy()(iapp_get_identity_policy)
            iapp_cls.verify_identity()(iapp_verify_identity)
            if getattr(iapp_cls, 'authn_provider', None):
                iapp_cls.authn_provider()(iapp_authnpolicy.get_app)
        else:
            iapp_cls.identity_policy()(get_identity_policy)
            iapp_cls.verify_identity()(verify_identity)
            if getattr(iapp_cls, 'authn_provider', None):
                iapp_cls.authn_provider()(authnpolicy.get_app)

        iapp_cls.init_settings(settings)
        iapp_cls._raw_settings = settings
        iapp_cls.commit()

    app.identity_policy()(get_identity_policy)
    app.verify_identity()(verify_identity)
    if authnpolicy.app_cls:
        app.authn_provider()(lambda: authnpolicy.app_cls())
    app.init_settings(settings)
    app._raw_settings = settings

    if settings['application']['development_mode']:
        os.environ['MOREPATH_TEMPLATE_AUTO_RELOAD'] = "1"

    app.commit()

    celery_settings = settings['worker']['celery_settings']
    app.celery.conf.update(**celery_settings)
    application = app()
    return application
Beispiel #25
0
def run():   # pragma: no cover
    morepath.autoscan()
    morepath.run(App())
Beispiel #26
0
def make_app():
    morepath.autoscan()
    App.commit()
    return App()
Beispiel #27
0
def run():   # pragma: no cover
    App.setting('storage', 'path')(default_storage_directory)
    morepath.autoscan()
    morepath.run(App())
def run():
    morepath.autoscan()
    morepath.run(App())
Beispiel #29
0
# for 'autogenerate' support.  These must be set
# up to hold just those tables targeting a
# particular database. table.tometadata() may be
# helpful here in case a "copy" of
# a MetaData is needed.
# from myapp import mymodel
# target_metadata = {
#       'engine1':mymodel.metadata1,
#       'engine2':mymodel.metadata2
# }

from morpfw.crud.storage.sqlstorage import Base
import morpcc.tests.democms
import morepath

morepath.autoscan()
morepath.scan(morpcc.tests.democms)
target_metadata = {'default': Base.metadata}

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
Beispiel #30
0
def run():  # pragma: no cover
    App.setting("storage", "path")(default_storage_directory)
    morepath.autoscan()
    morepath.run(App())
Beispiel #31
0
def app():
    morepath.autoscan()
    EkklesiaBrowserApp.commit()
    app = EkklesiaBrowserApp()
    app.babel_init()
    return app
Beispiel #32
0
def wsgi_factory():
    morepath.autoscan()
    morepath.scan()
    morepath.commit()
    return App()
Beispiel #33
0
def paths():
    morepath.autoscan()
    App.commit()
    path_tool(App)
def wsgi_factory():
    morepath.autoscan()
    morepath.scan()
    App.commit()
    return App()
Beispiel #35
0
def run():  # pragma: no cover
    App.setting('storage', 'path')(default_storage_directory)
    morepath.autoscan()
    morepath.run(App())