예제 #1
0
파일: app.py 프로젝트: mdheller/via3
def create_app(_=None, **settings):
    """Configure and return the WSGI app."""
    config = pyramid.config.Configurator(settings=load_settings(settings))

    config.include("pyramid_jinja2")
    config.include("via.views")
    config.include("h_pyramid_sentry")

    # Configure Pyramid so we can generate static URLs
    static_path = resource_filename("via", "static")
    cache_buster = PathCacheBuster(static_path)
    print(f"Cache buster salt: {cache_buster.salt}")

    config.add_static_view(name="static", path="via:static")
    config.add_cache_buster("via:static", cachebust=cache_buster)

    app = WhiteNoise(
        config.make_wsgi_app(),
        index_file=True,
        # Config for serving files at static/<salt>/path which are marked
        # as immutable
        root=static_path,
        prefix=cache_buster.immutable_path,
        immutable_file_test=cache_buster.get_immutable_file_test(),
    )

    app.add_files(
        # Config for serving files at / which are marked as mutable. This is
        # for robots.txt and / -> index.html
        root=resource_filename("via", "static"),
        prefix="/",
    )

    return app
예제 #2
0
def main(global_config, **settings):
    """
	This function returns a Pyramid WSGI application.
	"""

    # Database
    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    birda.models.DBSession.configure(bind=engine)

    # Authentication / Authorization
    session_factory = pyramid.session.UnencryptedCookieSessionFactoryConfig(
        settings['session.secret'])

    authn_policy = pyramid.authentication.SessionAuthenticationPolicy()
    authz_policy = pyramid.authorization.ACLAuthorizationPolicy()

    # Config creation
    config = pyramid.config.Configurator(
        settings=settings,
        root_factory=birda.models.acl.RootFactory,
        authentication_policy=authn_policy,
        authorization_policy=authz_policy,
        session_factory=session_factory)

    # Disabling exception logger in order to avoid conflicts with cornice
    # (exc_logger will be removed in .ini sometime in the future...)
    config.add_settings(handle_exceptions=False)

    # Tailorization of default pyramid json renderer
    config.add_renderer('json', define_json_renderer(settings))

    # Scan modules for cornice services
    #config.include("birda.services")
    config.include('cornice')
    config.scan("birda.services")

    # Add non JSON API routes
    birda.views.add_routes(config)
    config.scan()

    # Import all birda.models modules (necessary?)
    #config.scan('birda.models')

    config.add_subscriber(add_cors_headers_response_callback,
                          pyramid.events.NewRequest)

    # Activate and set application wide services (singletons)
    forms_factory = FormsFactory(settings)
    individuals_factory = IndividualsFactory(settings, forms_factory)

    config.include('pyramid_services')
    config.register_service(forms_factory,
                            iface=IFormsFactory,
                            name='FormsFactory')
    config.register_service(individuals_factory,
                            iface=IIndividualsFactory,
                            name='IndividualsFactory')

    # Make and run the application
    return config.make_wsgi_app()
예제 #3
0
def main(global_config, **settings):
    """Return a Pyramid WSGI application."""

    settings.setdefault('mako.directories', 'porygo_nz:templates')

    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    porygo_nz.db.DBSession.configure(bind=engine)

    config = pyramid.config.Configurator(
        settings=settings, root_factory=porygo_nz.resources.get_root)

    config.include('pyramid_mako')

    config.add_static_view('static', 'porygo_nz:static')

    config.add_request_method(porygo_nz.db.request_session,
                              name='db',
                              reify=True)
    config.add_request_method(porygo_nz.request_methods.show_abilities,
                              reify=True)
    config.add_request_method(porygo_nz.request_methods.show_hidden_abilities,
                              reify=True)

    config.scan()

    return config.make_wsgi_app()
예제 #4
0
def main(global_config, **settings):
    # Parse our couchdb secrets
    with open(settings['tractdb_couchdb_secrets']) as f:
        config = yaml.safe_load(f)
    settings['tractdb_couchdb_secrets'] = config

    # Parse our pyramid secrets
    with open(settings['tractdb_pyramid_secrets']) as f:
        config = yaml.safe_load(f)
    settings['tractdb_pyramid_secrets'] = config

    # Configure our pyramid app
    config = pyramid.config.Configurator(settings=settings)

    pyramid_secret = settings['tractdb_pyramid_secrets']['pyramid_secret']

    # Authentication and Authorization
    pyramid_secret = settings['tractdb_pyramid_secrets']['authtktauthenticationpolicy_secret']
    policy_authentication = pyramid.authentication.AuthTktAuthenticationPolicy(
        pyramid_secret, hashalg='sha512'
    )
    policy_authorization = pyramid.authorization.ACLAuthorizationPolicy()

    config.set_authentication_policy(policy_authentication)
    config.set_authorization_policy(policy_authorization)

    # Application views
    config.include('cornice')
    config.scan('tractdb_pyramid.views')

    # Make the app
    app = config.make_wsgi_app()

    return app
예제 #5
0
def main(global_config, **settings):
    # Keys that start with secrets need to be loaded from file
    settings['secrets'] = {}
    secrets = [key_original for key_original in settings.keys() if key_original.startswith('secrets.')]
    for key_original in secrets:
        path = settings[key_original]
        key = key_original[len('secrets.'):]

        with open(settings[key_original]) as f:
            config = yaml.safe_load(f)
        settings['secrets'][key] = config

        del settings[key_original]

    # Configure our pyramid app
    config = pyramid.config.Configurator(settings=settings)

    # Authentication and Authorization
    pyramid_secret = settings['secrets']['pyramid']['authtktauthenticationpolicy_secret']
    policy_authentication = pyramid.authentication.AuthTktAuthenticationPolicy(
        pyramid_secret, hashalg='sha512'
    )
    policy_authorization = pyramid.authorization.ACLAuthorizationPolicy()

    config.set_authentication_policy(policy_authentication)
    config.set_authorization_policy(policy_authorization)

    # Application views
    config.scan('tractdb_pyramid.views')

    # Make the app
    app = config.make_wsgi_app()

    return app
예제 #6
0
파일: __init__.py 프로젝트: caiok/bird-a
def main(global_config, **settings):
	"""
	This function returns a Pyramid WSGI application.
	"""

	# Database
	engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
	birda.models.DBSession.configure(bind=engine)

	# Authentication / Authorization
	session_factory = pyramid.session.UnencryptedCookieSessionFactoryConfig(
		settings['session.secret']
	)

	authn_policy = pyramid.authentication.SessionAuthenticationPolicy()
	authz_policy = pyramid.authorization.ACLAuthorizationPolicy()

	# Config creation
	config = pyramid.config.Configurator(
		settings=settings,
		root_factory=birda.models.acl.RootFactory,
		authentication_policy=authn_policy,
		authorization_policy=authz_policy,
		session_factory=session_factory
	)

	# Disabling exception logger in order to avoid conflicts with cornice
	# (exc_logger will be removed in .ini sometime in the future...)
	config.add_settings(handle_exceptions=False)
	
	# Tailorization of default pyramid json renderer
	config.add_renderer('json', define_json_renderer(settings))	
	
	# Scan modules for cornice services
	#config.include("birda.services")
	config.include('cornice')
	config.scan("birda.services")

	# Add non JSON API routes
	birda.views.add_routes(config)
	config.scan()

	# Import all birda.models modules (necessary?)
	#config.scan('birda.models')

	config.add_subscriber(add_cors_headers_response_callback, pyramid.events.NewRequest)
	
	# Activate and set application wide services (singletons)
	forms_factory = FormsFactory(settings)
	individuals_factory = IndividualsFactory(settings, forms_factory)
	
	config.include('pyramid_services')
	config.register_service(forms_factory, iface=IFormsFactory, name='FormsFactory')
	config.register_service(individuals_factory, iface=IIndividualsFactory, name='IndividualsFactory')

	# Make and run the application
	return config.make_wsgi_app()
예제 #7
0
def main(global_config, **settings):
    config = pyramid.config.Configurator(settings=settings)
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('home', '/')
    config.add_route('away_mode', '/away_mode')
    config.add_route('status', '/status')
    config.scan()
    app = config.make_wsgi_app()
    return app
예제 #8
0
def main() -> pyramid.router.Router:
    """ This function returns a Pyramid WSGI application.
    """
    settings: Final = sample.application.settings()
    with pyramid.config.Configurator(settings=settings) as config:
        config.include('.views.routes')
        _init_repository(config)
        _init_domain(config)
        return config.make_wsgi_app()
예제 #9
0
def _make_application(*, geoip, socket):
    """Construct a Pyramid WSGI application.

    This creates a central Pyramid configurator then adds all routes, views
    and Jinja2 configuration to it.

    :mod:`pyramid_jinja2` is included into the configuration. The search path
    for Jinja2 is set to the ``templates/`` directory. The Jinja2 syntax is
    modified so that it uses square brackets instead of curly ones. E.g.
    ``{{foo}}`` becomes ``[[foo]]``. This applies to Jinja2 statements as
    well as comments.

    A route and view is added for ``/`` which serves the Angular application.
    A default 'not found' view is also added which also serves the Angular
    application. This is so that the Angular ``$location`` service can use
    *HTML5 mode* routing. Because of this there is no guarantee that a matched
    route will be set for the current request inside the entry point template.
    E.g. you can't use ``request.current_route_url``.

    Static views are added for the ``external``, ``scripts``, ``styles``,
    ``images``, ``templates`` and ``data`` directories. These are all served
    directly from the route. E.g. templates are served from ``/templates/``.

    The configuration for Steam OpenID authentication and the location
    service is added.

    :param pathlib.Path geoip: the path to the GeoIP database to use for
        the location service.
    :param str socket: the websocket URL the UI should connect to.

    :return: a WSGI application.
    """
    config = pyramid.config.Configurator(settings={
        "pyramid.reload_templates": True,
    })
    config.include("pyramid_jinja2")
    config.add_jinja2_search_path(__name__ + ":templates/")
    config.add_route("main", "/")
    config.add_view(route_name="main", renderer="main.jinja2")
    config.add_notfound_view(_404, renderer="main.jinja2")
    for static in ["external", "scripts",
                   "styles", "images", "templates", "data"]:
        config.add_static_view(static, "{}:{}/".format(__name__, static))
    _configure_authentication(config)
    _configure_location(config, geoip)
    config.commit()
    jinja2_env = config.get_jinja2_environment()
    jinja2_env.block_start_string = "[%"
    jinja2_env.block_end_string = "%]"
    jinja2_env.variable_start_string = "[["
    jinja2_env.variable_end_string = "]]"
    jinja2_env.comment_start_string = "[#"
    jinja2_env.comment_end_string = "#]"
    jinja2_env.globals["socket"] = socket
    return config.make_wsgi_app()
예제 #10
0
파일: wsgi.py 프로젝트: jean/keas.kmi
def application_factory(global_config, **kw):
    storage_dir = os.path.abspath(kw['storage-dir'])
    if not os.path.exists(storage_dir):
        os.mkdir(storage_dir)
    global FACILITY
    FACILITY = facility.KeyManagementFacility(storage_dir)
    config =  pyramid.config.Configurator(
        root_factory=get_facility, package=keas.kmi)
    config.include('pyramid_zcml')
    config.load_zcml('configure.zcml')
    return config.make_wsgi_app()
예제 #11
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = pyramid.config.Configurator(settings=settings)
    # Add JSON as default renderer
    config.add_renderer(None, renderers.JSON())
    config.include('pyramid_jwt')
    config.include('.security')
    config.include('.models')
    config.include('.resources')
    config.scan()
    return config.make_wsgi_app()
예제 #12
0
def app():
    """Configure and return the WSGI app."""
    config = pyramid.config.Configurator(settings=settings())
    config.add_static_view(name="static", path="static")
    config.include("pyramid_jinja2")
    config.registry.settings["jinja2.filters"] = {
        "static_path": "pyramid_jinja2.filters:static_path_filter",
        "static_url": "pyramid_jinja2.filters:static_url_filter"
    }
    config.include("bouncer.views")
    config.include("bouncer.sentry")
    return config.make_wsgi_app()
예제 #13
0
def app():
    """Configure and return the WSGI app."""
    config = pyramid.config.Configurator(settings=settings())
    config.add_static_view(name="static", path="static")
    config.include("pyramid_jinja2")
    config.registry.settings["jinja2.filters"] = {
        "static_path": "pyramid_jinja2.filters:static_path_filter",
        "static_url": "pyramid_jinja2.filters:static_url_filter"
    }
    config.include("bouncer.views")
    config.include("bouncer.sentry")
    return config.make_wsgi_app()
예제 #14
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    model.setup()

    session_factory = session_factory_from_settings(settings)
    
    config = Configurator(
        settings=settings,
        root_factory=security.RootFactory,
        authentication_policy=AuthTktAuthenticationPolicy(
            settings["cookie_secret"],
            callback=security.group_finder),
        authorization_policy=ACLAuthorizationPolicy())

    config.set_request_factory(security.RequestWithUserAttribute)
    config.set_session_factory(session_factory)
    config.add_static_view("static", "scrobble:static")
    config.add_route("home", "/",
                     view="scrobble.views.list_users",
                     view_renderer="list_users.mako")
    config.add_route("new_account", "/new_account",
                     view="scrobble.login.new_account",
                     view_renderer="new_account.mako")
    config.add_route("login", "/login",
                     view="scrobble.login.login")
    config.add_route("logout", "/logout",
                     view="scrobble.login.logout",
                     view_renderer="logout.mako")
    config.add_route("list_users", "/users",
                     view="scrobble.views.list_users",
                     view_renderer="list_users.mako")
    config.add_route("user_home", "/user/{user}",
                     view="scrobble.views.user_home",
                     view_renderer="user_home.mako")

    
    config.add_route("simulate_listen", "/simulate_listen",
                     view="scrobble.views.simulate_listen",
                     view_renderer="simulate.mako")

    config.add_route("api_login", "api/login")
    config.add_route("api_whoami", "api/whoami")
    config.add_route("api_track_listen", "api/track_listen")
    config.add_route("api_follow_user", "api/follow_user")
    config.add_route("api_unfollow_user", "api/unfollow_user")
    config.scan()
    return config.make_wsgi_app()
예제 #15
0
def main(global_config, **settings):
    config = pyramid.config.Configurator(settings={
        **settings,
        **global_config
    })

    config.include(_api)
    config.include(_cors)
    config.include(_db)
    config.include(_log)
    config.include(_processor)
    config.include(_renderers)
    config.include(_static)

    return config.make_wsgi_app()
예제 #16
0
def main(global_config, **settings):
    settings.setdefault("jinja2.filters", "")
    settings["jinja2.filters"] += "\n".join([
        "",
        "to_json = asp.app:to_json_filter",
    ])

    config = pyramid.config.Configurator(settings=settings)
    config.registry.games = {}
    config.registry.texts = json.loads(
        pkg_resources.resource_string(__name__, "texts.json")
    )
    config.include("asp.www.home")
    config.scan("asp.www")

    return config.make_wsgi_app()
예제 #17
0
파일: app.py 프로젝트: hypothesis/via
def create_app(_=None, **settings):
    """Configure and return the WSGI app."""
    config = pyramid.config.Configurator(settings=load_settings(settings))

    config.include("pyramid_exclog")
    config.include("pyramid_jinja2")
    config.include("pyramid_services")
    config.include("h_pyramid_sentry")

    config.include("via.views")
    config.include("via.services")

    # Configure Pyramid so we can generate static URLs
    static_path = str(importlib_resources.files("via") / "static")
    cache_buster = PathCacheBuster(static_path)
    print(f"Cache buster salt: {cache_buster.salt}")

    config.add_static_view(name="static", path="via:static")
    config.add_cache_buster("via:static", cachebust=cache_buster)

    # Make the CheckmateClient object available as request.checkmate.
    config.add_request_method(ViaCheckmateClient, reify=True, name="checkmate")

    config.add_tween("via.tweens.robots_tween_factory")

    # Add this as near to the end of your config as possible:
    config.include("pyramid_sanity")

    app = WhiteNoise(
        config.make_wsgi_app(),
        index_file=True,
        # Config for serving files at static/<salt>/path which are marked
        # as immutable
        root=static_path,
        prefix=cache_buster.immutable_path,
        immutable_file_test=cache_buster.get_immutable_file_test(),
    )

    app.add_files(
        # Config for serving files at / which are marked as mutable. This is
        # for / -> index.html
        root=static_path,
        prefix="/",
    )

    return app
예제 #18
0
    def test_make_wsgi_app(self):
        import pyramid.config
        from pyramid.router import Router
        from pyramid.interfaces import IApplicationCreated

        manager = DummyThreadLocalManager()
        config = self._makeOne()
        subscriber = self._registerEventListener(config, IApplicationCreated)
        config.manager = manager
        app = config.make_wsgi_app()
        self.assertEqual(app.__class__, Router)
        self.assertEqual(manager.pushed['registry'], config.registry)
        self.assertEqual(manager.pushed['request'], None)
        self.assertTrue(manager.popped)
        self.assertEqual(pyramid.config.global_registries.last, app.registry)
        self.assertEqual(len(subscriber), 1)
        self.assertTrue(IApplicationCreated.providedBy(subscriber[0]))
        pyramid.config.global_registries.empty()
예제 #19
0
파일: test_init.py 프로젝트: Pylons/pyramid
    def test_make_wsgi_app(self):
        import pyramid.config
        from pyramid.router import Router
        from pyramid.interfaces import IApplicationCreated

        manager = DummyThreadLocalManager()
        config = self._makeOne()
        subscriber = self._registerEventListener(config, IApplicationCreated)
        config.manager = manager
        app = config.make_wsgi_app()
        self.assertEqual(app.__class__, Router)
        self.assertEqual(manager.pushed['registry'], config.registry)
        self.assertEqual(manager.pushed['request'], None)
        self.assertTrue(manager.popped)
        self.assertEqual(pyramid.config.global_registries.last, app.registry)
        self.assertEqual(len(subscriber), 1)
        self.assertTrue(IApplicationCreated.providedBy(subscriber[0]))
        pyramid.config.global_registries.empty()
예제 #20
0
파일: imsa.py 프로젝트: sblask/imsa
def server_start(arguments):
    try:
        __configure_logging(arguments)
        with pyramid.config.Configurator() as config:
            __discover_routes(config)
            # configure exception_view_config
            config.scan()
            app = config.make_wsgi_app()

        logger.info('Start server')
        server = wsgiref.simple_server.make_server(
            IP_ADDRESS,
            arguments.port,
            app,
            handler_class=LoggingWSGIRequestHandler,
        )
        State.get_instance().server = server
        logger.info('Accept requests')
        server.serve_forever()
    except Exception:
        logger.exception('Error starting server')
예제 #21
0
def main(global_config, **settings):
    # Keys that start with secrets need to be loaded from file
    settings['secrets'] = {}
    secrets = [
        key_original for key_original in settings.keys()
        if key_original.startswith('secrets.')
    ]
    for key_original in secrets:
        path = settings[key_original]
        key = key_original[len('secrets.'):]

        with open(settings[key_original]) as f:
            config = yaml.safe_load(f)
        settings['secrets'][key] = config

        del settings[key_original]

    # Configure our pyramid app
    config = pyramid.config.Configurator(settings=settings)

    # Authentication and Authorization
    pyramid_secret = settings['secrets']['pyramid'][
        'authtktauthenticationpolicy_secret']
    policy_authentication = pyramid.authentication.AuthTktAuthenticationPolicy(
        pyramid_secret, hashalg='sha512')
    policy_authorization = pyramid.authorization.ACLAuthorizationPolicy()

    config.set_authentication_policy(policy_authentication)
    config.set_authorization_policy(policy_authorization)

    # Application views
    config.scan('tractdb_pyramid.views')

    # Make the app
    app = config.make_wsgi_app()

    return app
예제 #22
0
def init_wsgi_app() -> pyramid.router.Router:
    config = pyramid.config.Configurator(
        settings={
            'pyramid.includes': [
                'pyramid_jinja2',
                'pyramid_tm',
            ],
            'pyramid.reload_templates': True,
        })
    init_json_renderer(config)

    for name, path, method in [
        ('index', "/", 'GET'),
        ('api_create_step', "/api/steps", 'POST'),
        ('api_get_step', "/api/steps/{step_id:\d+}", 'GET'),
        ('api_update_step', "/api/steps/{step_id:\d+}", 'PUT'),
    ]:
        config.add_route(name, path, request_method=method)
    config.scan()

    config.add_static_view('static', '../static', cache_max_age=1)
    config.commit()

    return config.make_wsgi_app()
예제 #23
0
def create_app(global_config, **settings):
    config = pyramid.config.Configurator(settings=settings)
    _configure_routes(config)
    return config.make_wsgi_app()
예제 #24
0
파일: app.py 프로젝트: mobyle2/mf-pyramid
    Dashboard.set_connection(connection)

    Dashboard.add_dashboard([User, Group, SuperGroup],config,'/test')

    renderer = mf.renderer.TextChoiceRenderer(User,'email','')
    renderer.limit([ 'nomail', '*****@*****.**', 'sample@nomail' ])
    renderer.add_extra_control('<button class="btn btn-info">Fake button</button>')

    renderer = User.get_renderer('groupRef')
    renderer.set_reference(Group)

    groupid_renderer = mf.renderer.SimpleReferenceRenderer(User,'groupid',Group)

    # automatically serialize bson ObjectId to Mongo extended JSON
    json_renderer = JSON()

    def objectId_adapter(obj, request):
        return json_util.default(obj)
    def datetime_adapter(obj, request):
        return json_util.default(obj)
    json_renderer.add_adapter(ObjectId, objectId_adapter)
    json_renderer.add_adapter(datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)

    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 6789, app)
    server.serve_forever()
    

예제 #25
0
def main():
    with pyramid.config.Configurator() as config:
        config.add_route("hello", "/")
        config.add_view(handle_edit_request, route_name="hello")
        app = config.make_wsgi_app()
        return app
예제 #26
0
def main(global_config, **settings):
    config = pyramid.config.Configurator(settings=settings)
    config.include("geekie.sms.messages")
    return config.make_wsgi_app()
예제 #27
0
def app():
    config = pyramid.config.Configurator()
    config.include('pyramid_scales')
    return config.make_wsgi_app()
예제 #28
0
def app():
    config = pyramid.config.Configurator()
    config.include('pyramid_scales')
    return config.make_wsgi_app()
예제 #29
0
def main(global_config, **settings):
    """
        This function returns a Pyramid WSGI application.
    """
    # Setup --------------------------------------------------------------------

    # Db
    init_DBSession(settings)

    # Pyramid Global Settings
    config = pyramid.config.Configurator(
        settings=settings,
        root_factory=TraversalGlobalRootFactory)  # , autocommit=True

    def assert_settings_keys(keys):
        for settings_key in key:
            assert config.registry.settings.get(settings_key)

    # Register Additional Includes ---------------------------------------------
    config.include(
        'pyramid_mako'
    )  # The mako.directories value is updated in the scan for addons. We trigger the import here to include the correct folders.

    # Reload on template change - Dedicated from pserve
    #template_filenames = map(operator.attrgetter('absolute'), file_scan(config.registry.settings['mako.directories']))
    #from pyramid.scripts.pserve import add_file_callback
    #add_file_callback(lambda: template_filenames)

    # Parse/Convert setting keys that have specified datatypes
    # Environment variables; capitalized and separated by underscores can override a settings key.
    # e.g.
    #   export KARAKARA_TEMPLATE_TITLE=Test
    #   can override 'karakara.template.title'
    for key in config.registry.settings.keys():
        value = os.getenv(
            key.replace('.', '_').upper(), ''
        ) if config.registry.settings['karakara.server.mode'] != 'test' else ''
        value = value or config.registry.settings[key]
        config.registry.settings[key] = convert_str_with_type(value)

    # Session identity
    config.add_request_method(partial(
        session_identity, session_keys={'id', 'admin', 'faves', 'user'}),
                              'session_identity',
                              reify=True)

    # Setup Cache Manager config in view
    setup_pyramid_cache_manager(config)
    # Setup Autoformat view processor
    setup_pyramid_autoformater(config)

    @post_view_dict_augmentation.register_pre_render_decorator()
    def add_paths_to_response_dict(request, response):
        response['paths'] = {
            'context': pyramid.traversal.resource_path(request.context),
            'queue': '',
        }
        try:
            queue_context = request.context.queue_context
            if queue_context:
                response['paths'].update(
                    template_helpers.paths_for_queue(queue_context.id))
        except AttributeError:
            pass

    # i18n
    config.add_translation_dirs(
        config.registry.settings['i18n.translation_dirs'])

    # Session Manager
    session_settings = extract_subkeys(config.registry.settings, 'session.')
    session_factory = SignedCookieSessionFactory(serializer=json_serializer,
                                                 **session_settings)
    config.set_session_factory(session_factory)

    from .model.actions import last_track_db_update

    def _last_track_db_update(request):
        return last_track_db_update()

    # Track DB Version ---------------------------------------------------------
    config.add_request_method(_last_track_db_update,
                              'last_track_db_update',
                              property=True,
                              reify=True)

    # Cachebust etags ----------------------------------------------------------
    #  crude implementation; count the number of tags in db, if thats changed, the etags will invalidate
    if not config.registry.settings['server.etag.cache_buster']:
        config.registry.settings[
            'server.etag.cache_buster'] = 'last_update:{0}'.format(
                str(last_track_db_update()))
        # TODO: Where is this used? How is this related to karakara.tracks.version?

    # Global State -------------------------------------------------------------
    config.registry.settings['karakara.tracks.version'] = random.randint(
        0, 20000000)

    # Search Config ------------------------------------------------------------
    import karakara.views.queue_search
    karakara.views.queue_search.search_config = read_json(
        config.registry.settings['karakara.search.view.config'])
    assert karakara.views.queue_search.search_config, 'search_config data required'

    # LogEvent -----------------------------------------------------------------

    log_event_logger = logging.getLogger('json_log_event')

    def log_event(request, **data):
        """
        It is expected that python's logging framework is used to output these
        events to the correct destination.
        Logstash can then read/process this log output for overview/stats
        """
        event = data.get('event')
        try:
            event = request.matched_route.name
        except Exception:
            pass
        try:
            event = request.context.__name__
        except Exception:
            pass
        data.update({
            'event': event,
            'session_id': request.session.get('id'),
            'ip': request.environ.get('REMOTE_ADDR'),
            'timestamp': now(),
        })
        log_event_logger.info(json_string(data))

    config.add_request_method(log_event)

    # WebSocket ----------------------------------------------------------------

    class NullAuthEchoServerManager(object):
        def recv(self, *args, **kwargs):
            pass

    socket_manager = NullAuthEchoServerManager()

    if config.registry.settings.get('karakara.websocket.port'):

        def authenticator(key):
            """Only admin authenticated keys can connect to the websocket"""
            cookie_name = config.registry.settings['session.cookie_name']
            if cookie_name in key:
                cookie = key
            else:
                cookie = '{0}={1}'.format(cookie_name, key)
            request = pyramid.request.Request({'HTTP_COOKIE': cookie})
            session_data = session_factory(request)
            return session_data and session_data.get('admin')

        def _int_or_none(setting_key):
            return int(config.registry.settings.get(setting_key)
                       ) if config.registry.settings.get(setting_key) else None

        try:
            _socket_manager = AuthEchoServerManager(
                authenticator=authenticator,
                websocket_port=_int_or_none('karakara.websocket.port'),
                tcp_port=_int_or_none('karakara.tcp.port'),
            )
            _socket_manager.start()
            socket_manager = _socket_manager
        except OSError:
            log.warn('Unable to setup websocket')

    def send_websocket_message(request, message):
        # TODO: This will have to be augmented with json and queue_id in future
        socket_manager.recv(
            message.encode('utf-8'))  # TODO: ?um? new_line needed?

    config.add_request_method(send_websocket_message)
    #config.registry['socket_manager'] = socket_manager

    # Login Providers ----------------------------------------------------------

    from .views.comunity_login import social_login
    social_login.user_store = ComunityUserStore()
    login_providers = config.registry.settings.get('login.provider.enabled')
    # Facebook
    if 'facebook' in login_providers:
        assert_settings_keys(
            ('login.facebook.appid', 'login.facebook.secret'),
            message=
            'To use facebook as a login provider appid and secret must be provided'
        )
        social_login.add_login_provider(
            FacebookLogin(
                appid=config.registry.settings.get('login.facebook.appid'),
                secret=config.registry.settings.get('login.facebook.secret'),
                permissions=config.registry.settings.get(
                    'login.facebook.permissions'),
            ))
    # Google
    if 'google' in login_providers:
        social_login.add_login_provider(
            GoogleLogin(client_secret_file=config.registry.settings.get(
                'login.google.client_secret_file'), ))
    # Firefox Persona (Deprecated technology but a useful reference)
    #if 'persona' in login_providers:
    #    social_login.add_login_provider(PersonaLogin(
    #        site_url=config.registry.settings.get('server.url')
    #    ))
    # No login provider
    if not login_providers and config.registry.settings.get(
            'karakara.server.mode') != 'test':
        # Auto login if no service keys are provided
        social_login.add_login_provider(NullLoginProvider())
        social_login.user_store = NullComunityUserStore()
    template_helpers.javascript_inline['comunity'] = social_login.html_includes

    # KaraKara request additions -----------------------------------------------

    from unittest.mock import patch

    def call_sub_view(request, view_callable, acquire_cache_bucket_func):
        """
        A wrapper for called view_callable's to allow subrequests to use correct cache_buckets
        """
        if not hasattr(request, 'cache_bucket'):
            # FFS - don't ask questions ... just ... (sigh) ... patch can ONLY patch existing attributes
            setattr(request, 'cache_bucket', 'some placeholder s***e')
        _cache_bucket = acquire_cache_bucket_func(request)
        with patch.object(request, 'cache_bucket', _cache_bucket):
            assert request.cache_bucket == _cache_bucket
            return view_callable(request)['data']

    config.add_request_method(call_sub_view)

    from .model_logic.queue_logic import QueueLogic
    config.add_request_method(QueueLogic, 'queue', reify=True)

    # Routes -------------------------------------------------------------------

    def settings_path(key):
        path = os.path.join(os.getcwd(), config.registry.settings[key])
        if not os.path.isdir(path):
            log.error('Unable to add_static_view {key}:{path}'.format(
                key=key, path=path))  #TODO: reaplce with formatstring
        return path

    # Static Routes
    config.add_static_view(
        name='ext',
        path=settings_path('static.externals'))  # cache_max_age=3600
    config.add_static_view(
        name='static',
        path=settings_path('static.assets'))  # cache_max_age=3600
    config.add_static_view(name='player', path=settings_path('static.player'))
    config.add_static_view(name='player2',
                           path=settings_path('static.player2'))

    # AllanC - it's official ... static route setup and generation is a mess in pyramid
    #config.add_static_view(name=settings["static.media" ], path="karakara:media" )
    config.add_static_view(
        name='files',
        path=config.registry.settings['static.processmedia2.config']
        ['path_processed'])

    # View Routes
    config.add_route('inject_testdata', '/inject_testdata')
    # Upload extras -----
    #config.add_static_view(name=settings['upload.route.uploaded'], path=settings['upload.path'])  # the 'upload' route above always matchs first
    config.add_route('upload', '/upload{sep:/?}{name:.*}')

    # Events -------------------------------------------------------------------
    config.add_subscriber(add_localizer_to_request, pyramid.events.NewRequest)
    config.add_subscriber(add_render_globals_to_template,
                          pyramid.events.BeforeRender)

    # Tweens -------------------------------------------------------------------
    if config.registry.settings.get(
            'karakara.server.mode'
    ) == 'development' and config.registry.settings.get(
            'karakara.server.postmortem'):
        config.add_tween('karakara.postmortem_tween_factory')

    # Return -------------------------------------------------------------------
    config.scan(ignore='.tests')
    config.scan('calaldees.pyramid_helpers.views')
    return config.make_wsgi_app()
예제 #30
0
import pyramid.config
import pyramid.response

from config import PING_MESSAGE


# noinspection PyUnusedLocal
def ping(request):
    return pyramid.response.Response(PING_MESSAGE.format(app='pyramid'))


with pyramid.config.Configurator() as config:
    config.add_route('ping', '/')
    config.add_view(ping, route_name='ping')
    app = config.make_wsgi_app()