Exemple #1
0
    def login(self):
        args = self.params()
        result = {}
        headers = {}
        registry = self.request.registry
        if args.get('external_login', False):
            data = {'external_login': args.pop('external_login')}
            data['preferredUsername'] = args.pop('user_name')
            data['profile'] = {'accounts': [args]}
            login_result = create_user(None, None, data)
            user = login_result.get('user', None)
            if not user:
                result = {'loggedin': False}
            else:
                headers = remember(self.request, get_oid(user))
                registry.notify(
                    LoggedIn(data['preferredUsername'], user, self.context,
                             self.request))
                result = {'loggedin': True}
        else:
            user, valid, headers = validate_user(self.context, self.request,
                                                 args)
            result = {'loggedin': valid}

        renderer = RendererHelper(name='json',
                                  package=caller_package(),
                                  registry=registry)
        response = renderer.render_view(self.request, result, self,
                                        self.context)
        response.headerlist.extend(headers)
        return response
Exemple #2
0
    def login(self):
        args = self.params()
        result = {}
        headers = {}
        registry = self.request.registry
        if args.get('external_login', False):
            data = {'external_login': args.pop('external_login')}
            data['preferredUsername'] = args.pop('user_name')
            data['profile'] = {'accounts': [args]}
            login_result = create_user(None, None, data)
            user = login_result.get('user', None)
            if not user:
                result = {'loggedin': False}
            else:
                headers = remember(self.request, get_oid(user))
                registry.notify(LoggedIn(
                    data['preferredUsername'], user,
                    self.context, self.request))
                result = {'loggedin': True}
        else:
            user, valid, headers = validate_user(
                self.context, self.request, args)
            result = {'loggedin': valid}

        renderer = RendererHelper(name='json', package=caller_package(),
                                  registry=registry)
        response = renderer.render_view(self.request, result, self,
                                        self.context)
        response.headerlist.extend(headers)
        return response
Exemple #3
0
def test_unicode():
    with testing.testConfig() as config:
        config.add_renderer(None, 'restfw.renderers.json_renderer')
        config.commit()
        renderer = RendererHelper(registry=config.registry)

        with open_pyramid_request(config.registry) as request:
            data = {'key': u'Значение'}
            res = renderer.render(data, system_values=None, request=request)
            assert res == u'{"key": "Значение"}'
Exemple #4
0
 def logout(self):
     headers = forget(self.request)
     result = {'loggedout': True}
     registry = self.request.registry
     renderer = RendererHelper(name='json', package=caller_package(),
                               registry=registry)
     response = renderer.render_view(self.request, result, self,
                                     self.context)
     response.headerlist.extend(headers)
     return response
Exemple #5
0
 def logout(self):
     headers = forget(self.request)
     result = {'loggedout': True}
     registry = self.request.registry
     renderer = RendererHelper(name='json',
                               package=caller_package(),
                               registry=registry)
     response = renderer.render_view(self.request, result, self,
                                     self.context)
     response.headerlist.extend(headers)
     return response
Exemple #6
0
 def callback(context, name, ob):
     renderer = settings.get('renderer')
     if isinstance(renderer, basestring):
         renderer = RendererHelper(name=renderer,
                                   package=info.module,
                                   registry=context.config.registry)
     elif IRendererInfo.providedBy(renderer):
         # create a new rendererinfo to clear out old registry on a
         # rescan, see https://github.com/Pylons/pyramid/pull/234
         renderer = renderer.clone(name=renderer.name,
                                   package=info.module,
                                   registry=context.config.registry)
     settings['renderer'] = renderer
     context.config.add_view(view=ob, **settings)
Exemple #7
0
    def test_basic(self):
        value = {'returned_val' : 'a test val from the result of view'}
        self.request.request_val = 'a test val from request.'
        self.request.session['session_val'] = 'a test val from session.'

        # 这里的value参数就对应于pyramid view的返回值
        helper = RendererHelper(name="pyramid.html",
                                registry=self.request.registry)
        html = helper.render(value, self.pyramid_system_value)

        # 检查结果
        self.assertTrue(u'a test val from the result of view' in html)
        self.assertTrue(u'a test val from request' in html)
        self.assertTrue(os.path.dirname(__file__) in html)
        self.assertTrue(u'a test val from session' in html)
Exemple #8
0
    def testing_add_renderer(self, path, renderer=None):
        """Unit/integration testing helper: register a renderer at
        ``path`` (usually a relative filename ala ``templates/foo.pt``
        or an asset specification) and return the renderer object.
        If the ``renderer`` argument is None, a 'dummy' renderer will
        be used.  This function is useful when testing code that calls
        the :func:`pyramid.renderers.render` function or
        :func:`pyramid.renderers.render_to_response` function or
        any other ``render_*`` or ``get_*`` API of the
        :mod:`pyramid.renderers` module.

        Note that calling this method for with a ``path`` argument
        representing a renderer factory type (e.g. for ``foo.pt``
        usually implies the ``chameleon_zpt`` renderer factory)
        clobbers any existing renderer factory registered for that
        type.

        .. note:: This method is also available under the alias
           ``testing_add_template`` (an older name for it).

        """
        from pyramid.testing import DummyRendererFactory
        helper = RendererHelper(name=path, registry=self.registry)
        factory = self.registry.queryUtility(IRendererFactory, name=helper.type)
        if not isinstance(factory, DummyRendererFactory):
            factory = DummyRendererFactory(helper.type, factory)
            self.registry.registerUtility(factory, IRendererFactory,
                                          name=helper.type)

        from pyramid.testing import DummyTemplateRenderer
        if renderer is None:
            renderer = DummyTemplateRenderer()
        factory.add(path, renderer)
        return renderer
Exemple #9
0
def register_layout_impl(cfg, view, name, context, renderer, layout,
                         route_name, use_global_views):
    if not layout:
        layout = None
    elif layout == '.':
        layout = ''

    if isinstance(renderer, string_types):
        renderer = RendererHelper(name=renderer, registry=cfg.registry)

    request_iface = IRequest
    if route_name is not None:
        request_iface = cfg.registry.getUtility(IRouteRequest, name=route_name)

    if use_global_views:
        request_iface = Interface

    if context is None:
        context = Interface

    mapper = getattr(view, '__view_mapper__', DefaultViewMapper)
    mapped_view = mapper()(view)

    info = LayoutInfo(name, layout, mapped_view, view, renderer,
                      cfg.__ptah_action__)
    cfg.registry.registerAdapter(info, (context, request_iface), ILayout, name)
Exemple #10
0
 def callback(context, name, ob):
     renderer = settings.get('renderer')
     if isinstance(renderer, basestring):
         renderer = RendererHelper(name=renderer,
                                   package=info.module,
                                   registry=context.config.registry)
     settings['renderer'] = renderer
     context.config.add_view(view=ob, **settings)
 def test_renderer_factory(self):
     from pyramid_genshi import renderer_factory
     from pyramid_genshi import GenshiTemplateRenderer
     from pyramid.renderers import RendererHelper
     path = self._get_template_path('minimal.genshi')
     info = RendererHelper(path)
     render = renderer_factory(info)
     self.assertEqual(render.path, path)
     self.assertIsInstance(render, GenshiTemplateRenderer)
Exemple #12
0
def page_view(request):
    # subpath = request.matchdict["subpath"]
    page = get_page(request.path_info)
    if page is None:
        raise HTTPNotFound

    renderer_name = "pylonsprojectjp:templates/page/" + page.template

    helper = RendererHelper(
        name=renderer_name,
        registry=request.registry)

    content = publish_parts(page.body, writer_name='html')['html_body']

    value = {
        "title": page.title,
        "content": content,
        }

    return helper.render_to_response(
        value, None, request=request)
Exemple #13
0
    def __call__(self, info):
        # Does this template exist
        name = info.name
        if ':' in name:
            name = name[name.index(':') + 1:]
        for package in reversed(self.packages):
            if pkg_resources.resource_exists(package.__name__, name):
                return renderer_factory(
                    RendererHelper(name, package, info.registry))

        # default to current package
        return renderer_factory(info)
Exemple #14
0
def register_snippet_impl(cfg, view, stype, context, renderer):
    if isinstance(renderer, string_types):
        renderer = RendererHelper(name=renderer, registry=cfg.registry)

    if view is None:
        view = ptah.View

    # register snippet
    if context is None:
        context = Interface

    cfg.registry.registerAdapter(SnippetRenderer(view, context, renderer),
                                 [context, Interface],
                                 ISnippet,
                                 name=stype)
Exemple #15
0
    def render(self, value, system_values, request=None):
        renderer = self.renderer
        context = system_values.get('context', None)
        try:
            layout = self.layout
            registry = self.registry
        except AttributeError:
            layout = self.layout = LayoutRenderer(self.layout_name)
            registry = self.registry = request.registry
            if self.name:
                renderer = self.renderer = RendererHelper(self.name,
                                                          registry=registry)

        if renderer:
            value = renderer.render(value, system_values, request)

        return layout(value, context, request)
Exemple #16
0
def render(request, asset, context=None, **options):
    registry = request.registry

    if context is not None:
        options['context'] = context

    templates = registry.get(ID_TEMPLATE)
    if templates is None:
        templates = registry[ID_TEMPLATE] = {}
        registry[ID_TEMPLATE_EXT] = tuple(
            name for name, _ in registry.getUtilitiesFor(IRendererFactory)
            if name.startswith('.'))

    if asset not in templates:
        r_name = None
        for ext in registry[ID_TEMPLATE_EXT]:
            if asset.endswith(ext):
                r_name = asset

        if not r_name:
            r_name = '%s.lt' % asset

        templates[asset] = RendererHelper(r_name, registry=registry)

    view = getattr(request, '__view__', None)
    if view is None:
        view = context

    request.__view__ = view

    options['view'] = view
    system = {
        'view': view,
        'renderer_info': templates[asset],
        'context': context,
        'request': request
    }

    result = templates[asset].render(options, system, request)

    request.__view__ = view
    return result
Exemple #17
0
def ux2_metarenderer_factory(info):
    """
    Use a custom renderer to choose between 'classic' and 'ux2' UI.
    """
    # Don't use metarenderer if we're specifcally already looking for
    # something in karl.ux2.  Also don't use metarender for any of the layouts.
    # We want those to be explicitly chosen from one UI or the other at the
    # point where they are used.
    if info.name.endswith('_layout.pt') or info.package is karl.ux2:
        return renderer_factory(info)

    # Does this template exist in ux2?
    name = info.name
    if ':' in name:
        name = name[name.index(':') + 1:]
    ux2_package = karl.ux2
    name = ux1_to_ux2_templates.get(name, name)
    if info.package.__name__.startswith('osi.'):
        import osi.ux2 as ux2_package
        if not pkg_resources.resource_exists(ux2_package.__name__, name):
            # Let karl.ux2 templates be used if not in osi.ux2
            ux2_package = karl.ux2
    if not pkg_resources.resource_exists(ux2_package.__name__, name):
        # There's not a UX2 version, so just return the same old renderer
        # you would normally use
        return renderer_factory(info)

    # Return a renderer that chooses classic versus ux2 based on cookie
    # in request.
    classic_renderer = renderer_factory(info)
    ux2_renderer = renderer_factory(
        RendererHelper(name, ux2_package, info.registry))

    def metarenderer(value, system):
        use_ux2 = system['request'].cookies.get('ux2_kachoo') == 'true'
        if use_ux2:
            if 'api' in value:
                del value['api']
            return ux2_renderer(value, system)
        return classic_renderer(value, system)

    return metarenderer
Exemple #18
0
def test_add_adapter():
    with testing.testConfig() as config:
        config.add_renderer(None, 'restfw.renderers.json_renderer')
        config.commit()
        renderer = RendererHelper(registry=config.registry)

        with open_pyramid_request(config.registry) as request:
            data = SomeClass(10)
            with pytest.raises(TypeError):
                res = renderer.render(data,
                                      system_values=None,
                                      request=request)

    with testing.testConfig() as config:
        config.add_renderer(None, 'restfw.renderers.json_renderer')
        config.commit()
        renderer = RendererHelper(registry=config.registry)
        add_adapter_into_json_renderer(SomeClass, some_adapter)
        add_adapter_into_json_renderer(SomeClass, some_adapter)  # no errors

        with open_pyramid_request(config.registry) as request:
            data = SomeClass(10)
            res = renderer.render(data, system_values=None, request=request)
            assert res == '10'
Exemple #19
0
def add_layout(cfg,
               name='',
               context=None,
               root=None,
               parent=None,
               renderer=None,
               route_name=None,
               use_global_views=True,
               view=None):
    """Registers a layout.

    :param name: Layout name
    :param context: Specific context for this layout.
    :param root:  Root object
    :param parent: A parent layout. None means no parent layout.
    :param renderer: A pyramid renderer
    :param route_name: A pyramid route_name. Apply layout only for
        specific route
    :param use_global_views: Apply layout to all routes. even is route
        doesnt use use_global_views.
    :param view: View callable


    Simple example with one default layout and 'page' layout.

    .. code-block:: python

      class PageLayout(object):
           ...

      config.add_layout('page', parent='page', renderer='my_package:template/page.pt')


    To use layout with pyramid view use ``renderer=ptah.renderer.layout('my_pkg:template/page.pt')``

    Example:

    .. code-block:: python

      config.add_view('
          index.html',
          renderer = ptah.renderer.layout('...'))

    in this example '' layout is beeing used. You can specify specific layout
    name for pyramid view ``ptah.renderer.layout('page', 'layout name')``

    """
    #    (scope, module,
    #     f_locals, f_globals, codeinfo) = venusian.getFrameInfo(sys._getframe(2))

    #    codeinfo = CodeInfo(
    #        codeinfo[0], codeinfo[1], codeinfo[2], codeinfo[3], module.__name__)

    discr = (LAYOUT_ID, name, context, route_name)

    intr = Introspectable(LAYOUT_ID, discr, name, 'ptah.renderer_layout')

    intr['name'] = name
    intr['context'] = context
    intr['root'] = root
    intr['renderer'] = renderer
    intr['route_name'] = route_name
    intr['parent'] = parent
    intr['use_global_views'] = use_global_views
    intr['view'] = view
    #    intr['codeinfo'] = codeinfo

    if not parent:
        parent = None
    elif parent == '.':
        parent = ''

    if isinstance(renderer, string_types):
        renderer = RendererHelper(name=renderer, registry=cfg.registry)

    if context is None:
        context = Interface

    def register():
        request_iface = IRequest
        if route_name is not None:
            request_iface = cfg.registry.getUtility(IRouteRequest,
                                                    name=route_name)

        if use_global_views:
            request_iface = Interface

        mapper = getattr(view, '__view_mapper__', DefaultViewMapper)
        mapped_view = mapper()(view)

        info = LayoutInfo(name, parent, mapped_view, view, renderer, intr)
        cfg.registry.registerAdapter(info, (root, request_iface, context),
                                     ILayout, name)

    cfg.action(discr, register, introspectables=(intr, ))
Exemple #20
0
 def add_template(self, path: AnyStr):
     logging.debug("path = %s", path)
     self._rs[path] = RendererHelper(name=path,
                                     package='heptet_app',
                                     registry=self._config.registry)
     logging.debug("renderer = %s", self._rs[path])
Exemple #21
0
 def _makeOne(self, *arg, **kw):
     from pyramid.renderers import RendererHelper
     return RendererHelper(*arg, **kw)