Пример #1
0
 def __init__(self,
              package,
              session_key=None,
              authn_policy=None,
              authz_policy=None,
              **settings):
     self.package = package
     self.session_key = session_key
     self.g = Namespace()
     session_factory = UnencryptedCookieSessionFactoryConfig(session_key, )
     settings['jinja2.directories'] = ['%s:templates' % package]
     self.config = Configurator(session_factory=session_factory,
                                settings=settings,
                                authentication_policy=authn_policy,
                                authorization_policy=authz_policy)
     self.config.begin()
     self.config.add_renderer(None, self.renderer_factory)
     self.config.add_renderer('.html', j2_renderer_factory)
     self.config.set_renderer_globals_factory(self.renderer_globals_factory)
     notfound_view = AppendSlashNotFoundViewFactory()
     self.config.add_view(notfound_view, context=NotFound)
     self.config.add_view(self.exc_handler,
                          context=httpexceptions.WSGIHTTPException)
     self.config.add_static_view('static', '%s:static' % self.package)
     self.config.add_subscriber(self.start_request, NewRequest)
     self.config.commit()
Пример #2
0
    def __init__(self, package,
                 session_key='sekret',
                 authn_policy=None, authz_policy=None,
                 **settings):
        """initial config for singleton baka framework

        :param import_name: the name of the application package
        :param session_key: secret key for session
        :param authn_policy: authenticate policy middleware function
        :param authz_policy: authorization policy middleware function
        :param config_schema: boolean value for trafaret validator
        :param settings: *optional dict settings for pyramid configuration
        """
        self.package = package
        session_factory = SignedCookieSessionFactory(session_key)
        settings.update({
            'secret_key': session_key,
            'session_factory': session_factory,
            'authentication_policy': authn_policy,
            'authorization_policy': authz_policy
        })

        self.config = self.configure(settings)
        self.config.registry.package = self.package
        log.info(self.config.registry)
        self.config.begin()
        self.config.add_view(AppendSlashNotFoundViewFactory(), context=NotFound)
        self.config.add_directive('add_ext', self.add_ext_config)

        self.config.registry.trafaret = None
        self.config.include(__name__)
        self.registry = _BakaExtensions
        _logging_format(self.config.get_settings())
        self.config.commit()
        print('🚀 started: Baka Framework')
Пример #3
0
        def decorator(func):
            def errfunc(exc, request):
                request.response.status = exc.status
                return func(exc)

            exc = httpexceptions.status_map.get(code)

            if exc is not None:
                view = errfunc
                if exc is NotFound:
                    view = AppendSlashNotFoundViewFactory(errfunc)
                self.config.add_view(view, context=exc)

            return func
Пример #4
0
        def decorator(wrapped):
            settings['renderer'] = settings.get('renderer', 'json')
            settings['permission'] = settings.get('permission,', NO_PERMISSION_REQUIRED)
            target = DottedNameResolver().maybe_resolve(wrapped)
            def err_func(context, request):
                if not isinstance(context, Exception):
                    context = request.exception or context
                request.response.status = context.status
                request.response.status_code = code
                return target(context, request)

            exc = type(httpexceptions.exception_response(code))
            if exc is not None:
                view = err_func
                if exc is NotFound:
                    view = AppendSlashNotFoundViewFactory(err_func)
            else:
                exc = Exception

            self.config.add_view(view, context=exc, **settings)

            return wrapped
Пример #5
0
 def _makeOne(self, notfound_view):
     from pyramid.view import AppendSlashNotFoundViewFactory
     return AppendSlashNotFoundViewFactory(notfound_view)
Пример #6
0
def factory(global_config, **settings):
    """Call to return a WSGI application."""

    # Bind the SQLAlchemy model classes to the database specified in the
    # ``settings`` provided.
    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)

    # Initialise the ``Configurator`` with authentication policy.
    auth_policy = RemoteUserAuthenticationPolicy()
    config = Configurator(settings=settings, authentication_policy=auth_policy)

    # Include external libraries.
    config.include('pyramid_assetgen')
    config.include('pyramid_weblayer')

    # Setup request and session factories.
    class CustomRequest(AssetGenRequestMixin, Request):
        pass

    config.set_request_factory(CustomRequest)
    config.set_session_factory(session_factory_from_settings(settings))

    # Add ``is_authenticated`` and ``user`` properties to the request.
    config.set_request_property(get_is_authenticated,
                                'is_authenticated',
                                reify=True)
    config.set_request_property(get_user, 'user', reify=True)

    # Tell the translation machinery where the message strings are.
    config.add_translation_dirs(settings['locale_dir'])

    # Expose `/static` and `/thumbs` directories, cached for two weeks,
    # specifying that ``settings['static_dir'] has an assetgen manifest
    # in it, and expose the panorama `/tour` files without caching.
    static_dir = settings['static_dir']
    thumbs_dir = settings['thumbnails_dir']
    tour_dir = settings['tour_dir']
    config.add_assetgen_manifest(static_dir)
    config.add_static_view('static', static_dir, cache_max_age=1209600)
    config.add_static_view('thumbs', thumbs_dir, cache_max_age=1209600)
    config.add_static_view('tour', tour_dir)

    # Configure a custom 404 that first tries to append a slash to the URL.
    not_found = AppendSlashNotFoundViewFactory(not_found_view)
    config.add_view(not_found, context='pyramid.httpexceptions.HTTPNotFound')

    # Expose dynamic views.
    for name, pattern in route_mapping:
        config.add_route(name, pattern)

    # Run a venusian scan to pick up the declerative configuration from this
    # and any included packages.
    config.scan()

    # Fake authentication for now.
    class AuthenticationMiddleware:
        def __init__(self, app):
            self.app = app

        def __call__(self, environ, start_response):
            environ['REMOTE_USER'] = '******'
            return self.app(environ, start_response)

    # Return a configured WSGI application.
    return AuthenticationMiddleware(config.make_wsgi_app())