Beispiel #1
0
 def RenderView(self, obj, name="", secure=True, raiseUnauthorized=False, codepage="utf-8"):
     """
     Render a view for the object.
     
     *name* is the name of the view to be looked up.
     
     If *secure* is true permissions of the current user are checked against the view. If the
     user lacks the necessary permissions and empty string is returned or if *raiseUnauthorized*
     is True HTTPForbidden is raised. 
     
     returns rendered result
     """
     # store original context to reset after calling render_view
     orgctx = self.request.context
     self.request.context = obj
     if not raiseUnauthorized:
         try:
             value = render_view(obj, self.request, name, secure)
             self.request.context = orgctx
         except HTTPForbidden:
             self.request.context = orgctx
             return u""
     else:
         try:
             value = render_view(obj, self.request, name, secure)
         except:
             self.request.context = orgctx
             raise
     self.request.context = orgctx
     if not value:
         return u""
     return unicode(value, codepage)
Beispiel #2
0
    def response(self):
        page = int(self.request.params.get('page') or 0)
        description_only = self.request.params.get('description_only', False)

        catalog = find_catalog(self.context, 'system')
        content_type = catalog['content_type']
        query = content_type.eq(self.context.target_content_type)
        if self.context.path is not None:
            path = catalog['path']
            query &= path.eq(self.context.path, include_origin=False)
        resultset = [i for i in query.execute()]
        resultset.sort(
            key=attrgetter(self.context.sort_field),
            reverse=self.context.sort_inverse)
        if description_only:
            resultset = [
                {'title': e.title,
                 'name': e.name,
                 'description': e.short_description}
                for e in resultset]
            page_to_show = slice(None)
        else:
            resultset = [str(render_view(e, self.request)) for e in resultset]
            page_to_show = slice(page, page + self.context.total_results or None)
        return {
            'title': self.context.title,
            'text': self.context.text,
            'items': resultset[page_to_show],
            'page': page,
            'pages': len(resultset),
        }
 def __call__(self):
     with GitClone(self.request.base_repo_name, self.request.base_repo_url) as repo:
         validationResults = self.validate(repo)
         repo.merge(self.request.head_repo_url)
         validationResutlsAfter = self.validate(repo)
         validationView = render_view((validationResults, validationResutlsAfter),
                 self.request, 'view')
Beispiel #4
0
    def RenderView(self, obj, name="", secure=True, raiseUnauthorized=False, codepage="utf-8"):
        """
        Render a view for the object.
        
        *name* is the name of the view to be looked up.
        
        If *secure* is true permissions of the current user are checked against the view. If the
        user lacks the necessary permissions and empty string is returned or if *raiseUnauthorized*
        is True HTTPForbidden is raised. 
        
        returns rendered result
        """
        # store original context to reset after calling render_view
        orgctx = self.request.context
        orgresp = self.request.response
        orgname = self.request.view_name

        self.request.context = obj
        self.request.response = Response()
        self.request.view_name = name
        try:
            value = render_view(obj, self.request, name, secure)
            if value is None:
                value = ""
        except HTTPNotFound:
            value = "Not found!"
        except HTTPForbidden:
            value = ""
        finally:
            self.request.context = orgctx
            self.request.response = orgresp
            self.request.view_name = orgname

        return unicode(value, codepage)
def _render_view_on_slot_event(view_name, event, params):
    context = event.object
    request = event.request

    view_request = Request.blank(
        "{0}/{1}".format(request.path.rstrip('/'), view_name),
        base_url=request.application_url,
        POST=_encode(params),
        )

    post_items = request.POST.items()
    if post_items:
        view_request.POST.extend(post_items)

    # This is quite brittle:
    for name in REQUEST_ATTRS_TO_COPY:
        setattr(view_request, name, getattr(request, name))

    try:
        result = render_view(
            context,
            view_request,
            view_name,
            )
    except PredicateMismatch:
        return None
    else:
        return result.decode('utf-8')
Beispiel #6
0
def _render_view_on_slot_event(view_name, event, params):
    context = event.object
    request = event.request

    view_request = request.__class__.blank(
        "{0}/{1}".format(request.path.rstrip('/'), view_name),
        base_url=request.application_url,
        POST=_encode(params)
    )

    if request.POST:
        view_request.POST.update(request.POST)

    # This is quite brittle:
    for name in REQUEST_ATTRS_TO_COPY:
        setattr(view_request, name, getattr(request, name))
    setattr(view_request, 'kotti_slot', event.name)

    try:
        result = render_view(context, view_request, view_name)
    except (PredicateMismatch, HTTPForbidden):
        return None
    if isinstance(context, HTTPException):
        return None
    return result.decode('utf-8')
    def content(self):

        """ We may or may not use a complex layout... """

        if not self.context.__data__['use_complex_layout']:

            return self.context.__data__['text']

        html = []

        self.request.is_edit = self.is_edit

        height = 0

        for block in self.context.blocks:

            try:
                block_height = int(float(block.get("height", "200px")[:-2]))
                block_top = int(float(block.get("top", "10px")[:-2]))

                height = max(height, block_top + block_height)
            except:
                pass

            html.append(render_view(block, self.request))

        return """<div class="content" style="min-height: %spx">%s</div>""" \
                % (height + 20, "".join(html))
Beispiel #8
0
def build_chrome(args):
    """
    Build the Chrome extension. You can supply the base URL of an h
    installation with which this extension will communicate, such as
    "http://localhost:5000" (the default) when developing locally or
    "https://hypothes.is" to talk to the production Hypothesis application.

    By default, the extension will load static assets (JavaScript/CSS/etc.)
    from the application you specify. This can be useful when developing, but
    when building a production extension for deployment to the Chrome Store you
    will need to specify an assets URL that links to the built assets within
    the Chrome Extension, such as:

        chrome-extension://<extensionid>/public
    """
    paster.setup_logging(args.config_uri)

    os.environ['WEBASSETS_BASE_DIR'] = os.path.abspath('./build/chrome/public')
    if args.assets is not None:
        os.environ['WEBASSETS_BASE_URL'] = args.assets

    env = get_env(args.config_uri, args.base)

    # Prepare a fresh build.
    clean('build/chrome')
    os.makedirs('build/chrome')

    # Bundle the extension assets.
    webassets_env = env['request'].webassets_env
    content_dir = webassets_env.directory
    os.makedirs(content_dir)
    copytree('h/browser/chrome/content', 'build/chrome/content')
    copytree('h/browser/chrome/help', 'build/chrome/help')
    copytree('h/browser/chrome/images', 'build/chrome/images')
    copytree('h/browser/chrome/lib', 'build/chrome/lib')
    copytree('h/static/images', 'build/chrome/public/images')
    shutil.copyfile(
        'h/static/scripts/blocklist.js', 'build/chrome/lib/blocklist.js')

    # Render the sidebar html.
    if webassets_env.url.startswith('chrome-extension:'):
        build_extension_common(env, bundle_app=True)
        env['request'].layout_manager.layout.csp = ''
        with open(content_dir + '/app.html', 'w') as fp:
            data = render_view(env['root'], env['request'], 'viewer')
            fp.write(data)
        shutil.copyfile('h/static/icomoon.css',
                        'build/chrome/public/icomoon.css')
    else:
        build_extension_common(env)

    # Render the manifest.
    with open('build/chrome/manifest.json', 'w') as fp:
        data = chrome_manifest(env['request'])
        fp.write(data)

    # Render the blocklist as a JSON file.
    with open('build/chrome/blocklist.json', 'w') as fp:
        fp.write(json.dumps(env['registry'].settings['h.blocklist']))
    def __call__(self):
        
        block = self._find_block()

        if block:
            return {'content': render_view(block, self.request)}
        else:
            return {'content': 'Not found'}
 def __call__(self, name='', secure=True):
     # Decode to utf8, else it's gonna throw UnicodeDecodeError
     try:
         return render_view(self.context, self.request, name, secure).decode("utf8")
     except AttributeError:
         #Handle none object
         pass
     return None
Beispiel #11
0
 def __call__(self):
     super(KeywordCloudView, self).__call__()
     if 'clear' in self.request.GET:
         CloudMaker(self.context, self.request).make_cloud(False)
     return {'keyword_cloud': render_view(self.context,
                                          self.request,
                                          'keyword-cloud-image'),
            }
Beispiel #12
0
def embed(context, request):
    assets_dir = request.webassets_env.directory
    embed_file = join(assets_dir, 'js/embed.js')

    setattr(request, 'view_name', 'embed.js')
    with open(embed_file, 'w') as f:
        f.write(render_view(context, request, name='embed.js'))
    delattr(request, 'view_name')
    def content(self):

        html = []

        for block in self.context.blocks:

            html.append(render_view(block, self.request))

        return "".join(html)
Beispiel #14
0
 def __call__(self, name='', secure=True):
     from pyramid.view import render_view
     # Decode to utf8, else it's gonna throw UnicodeDecodeError
     try:
         return render_view(self.context, self.request,
                 name, secure).decode("utf8")
     except AttributeError:
         pass
     return None
Beispiel #15
0
    def test_register_view(self):
        name = 'index.pt'
        from pyramid_skins.configuration import register_path
        register_path(self.config, os.path.join(path, 'skins'), indexes=[name])

        from pyramid.testing import DummyRequest
        from pyramid.view import render_view

        response = render_view('Hello world!', DummyRequest(), "")
        self.assertTrue(response is not None)
    def layout(self):

        html = []

        self.request.is_edit = self.is_edit

        for block in self.context.blocks:

            html.append(render_view(block, self.request))

        return "".join(html)
def test_it(config):
    config.set_todict(Dummy, to_dict_dummy, name="testing.json")
    config.add_view(dummy_view, name="dummy_view", renderer="testing.json")
    from pyramid.view import render_view

    context = testing.DummyResource()
    request = testing.DummyRequest()
    result = render_view(context, request, name="dummy_view")
    assert request.response.content_type == "application/json"
    import json

    assert json.loads(result.decode("utf-8")) == json.loads('{"dummy": {"value": "test"}, "extra": 100}')
    def save_block(self):

        """ but not really... we only create the proper html """

        clazz = Registry.get_type(self.request.params.get('type'))

        if not clazz:
            return {'html': ''}

        block = clazz(self.request.params.get("id"), **self.request.params)

        if block['type'] == "image":

            if self.request.params.get('mode') == 'add':

                img_id = self.context.generate_content_id(
                        self.request.params.get('img').filename)

                img = Image(img_id,
                        {'name': img_id,
                         'data': {
                             'name': self.request.params.get('img').filename,
                             'data': self.request.params.get('img').value
                             }
                        })

                self.context.add_content(img)

                block['img_url'] = '%s%s' % (self.url, img_id)

                self.request.is_edit = True

                return "%s" % render_view(block, self.request)

        self.request.is_edit = True

        return render_view(block, self.request)
Beispiel #19
0
    def test_skin_reload(self):
        from pyramid_skins.configuration import register_path
        import shutil
        import tempfile

        register_path(self.config, os.path.join(path, 'skins'))
        tmp = tempfile.mkdtemp()

        try:
            skins_dir = os.path.join(tmp, 'skins')
            os.mkdir(skins_dir)
            with open(os.path.join(skins_dir, 'index.pt'), 'wb') as f:
                f.write('<html><title>Alternative</title></html>')

            skins = self.register_skins([skins_dir])

            from pyramid_skins.renderer import renderer_factory
            self.config.add_renderer('skin', renderer_factory)

            def index(context, request):
                return {'context': context}

            self.config.add_view(index, name='index', renderer='skin')

            from pyramid.view import render_view
            from pyramid.threadlocal import get_current_request
            alsoProvides(get_current_request(), skins['skins']['interface'])
            result = render_view('Hello world!', get_current_request(), 'index')
            self.assertTrue('Alternative' in result)
            with open(os.path.join(skins_dir, 'index.pt'), 'wb') as f:
                f.write('<html><title>Other</title></html>')
            skins['skins']['skin'].configure()
            result = render_view('Hello world!', get_current_request(), 'index')
            self.assertTrue('Other' in result)
        finally:
            shutil.rmtree(tmp)
Beispiel #20
0
    def test_verify_output_bytestring(self):
        from pyramid.request import Request
        from pyramid.config import Configurator
        from pyramid.view import render_view
        from webob.compat import text_type
        config = Configurator(settings={})
        def view(request):
            request.response.text = text_type('<body></body>')
            return request.response

        config.add_view(name='test', view=view)
        config.commit()

        r = Request({})
        r.registry = config.registry
        self.assertEqual(render_view(object(), r, 'test'), b'<body></body>')
Beispiel #21
0
    def test_renderer(self):
        from pyramid_skins.configuration import register_path
        register_path(self.config, os.path.join(path, 'skins'))

        from pyramid_skins.renderer import renderer_factory
        self.config.add_renderer('skin', renderer_factory)

        def index(context, request):
            return {'context': context}

        self.config.add_view(index, name='index', renderer='skin')

        from pyramid.view import render_view
        from pyramid.threadlocal import get_current_request
        result = render_view('Hello world!', get_current_request(), 'index')
        self.assertTrue('Hello world' in result)
Beispiel #22
0
def _render_view_on_slot_event(view_name, event, params):
    context = event.object
    request = event.request
    view_request = Request.blank(
        "{0}/{1}".format(request.path, view_name),
        base_url=request.application_url,
        POST=_encode(params),
        )
    view_request.registry = request.registry
    try:
        result = render_view(
            context,
            view_request,
            view_name,
            )
    except PredicateMismatch:
        return None
    else:
        return result.decode('utf-8')
Beispiel #23
0
    def test_multiple_skins_other(self):
        from pyramid.threadlocal import get_current_request
        from pyramid.view import render_view
        from pyramid_skins.configuration import register_path
        from pyramid_skins.renderer import renderer_factory

        register_path(self.config, os.path.join(path, 'skins'))
        skins = self.register_skins([
            os.path.join(path, 'alt_skins'),
            os.path.join(path, 'other_skins')])
        self.config.add_renderer('skin', renderer_factory)

        def index(context, request):
            return {'context': context}

        self.config.add_view(index, name='index', renderer='skin')

        alsoProvides(get_current_request(), skins['other_skins']['interface'])
        result = render_view('Hello world!', get_current_request(), 'index')
        self.assertTrue('Other' in result)
 def sub(match):
     infos = match.groupdict()
     if infos['selfclosing'] is None and infos['content'] is None:
         return '<div class="alert alert-error">{0}</div>'.format(
             localizer.translate(
                 _("Snippet tag '${name}' not closed",
                   mapping=dict(name=infos['name']))))
     if infos['escapeopen'] and infos['escapeclose']:
         return ''.join((
             infos['escapeopen'],
             infos['name'],
             infos['arguments'],
             infos['selfclosing'],
             infos['escapeclose']))
     arguments = {}
     last_key = None
     for arg in infos['arguments'].split(' '):
         if '=' in arg:
             key, value = arg.split('=')
             key = key.strip()
             value = value.strip()
             arguments[key] = value
             last_key = key
         elif last_key is not None:
             arguments[last_key] = "%s %s" % (arguments[last_key], arg)
     arguments['body'] = infos['content']
     snippet_request = Request.blank(
         request.path + '/snippet-%s' % infos['name'],
         base_url=request.application_url,
         POST=urllib.urlencode(arguments))
     snippet_request.registry = request.registry
     result = render_view(
         context,
         snippet_request,
         'snippet-%s' % infos['name'])
     if result is None:
         return '<div class="alert alert-error">{0}</div>'.format(
             localizer.translate(
                 _("No snippet with name '${name}' registered.",
                   mapping=dict(name=infos['name']))))
     return result
Beispiel #25
0
 def dispatch(self, method, secure=False, request=None, **kw):
     """
     If *secure* is true permissions of the current user are checked against the view. If the
     user lacks the necessary permissions and empty string is returned or if *raiseUnauthorized*
     is True HTTPForbidden is raised. 
     
     returns rendered result
     """
     if not request:
         secure = False
         
     disprequest = testing.DummyRequest() #DispatchRequest()
     disprequest.context = self
     disprequest.POST = kw
     disprequest.method = "POST"
     disprequest.content_type = "dict"
     value = render_view(self, disprequest, method, secure)
     if value is None:
         value = {}
     else:
         value = json.loads(value)
     return value, disprequest.response.status
Beispiel #26
0
def app(context, request):
    assets_dir = request.webassets_env.directory
    app_file = join(assets_dir, 'app.html')
    request.accept = 'text/html'
    with open(app_file, 'w') as f:
        f.write(render_view(context, request, name='app'))
Beispiel #27
0
 def _callFUT(self, *arg, **kw):
     from pyramid.view import render_view
     return render_view(*arg, **kw)
Beispiel #28
0
def embed(embed_path, context, request):
    setattr(request, 'view_name', 'embed.js')
    with open(embed_path, 'w') as f:
        f.write(render_view(context, request, name='embed.js'))
    delattr(request, 'view_name')
Beispiel #29
0
def app(app_path, context, request):
    with open(app_path, 'w') as f:
        f.write(render_view(context, request, name='app.html'))
Beispiel #30
0
 def __call__(self, name='', secure=True):
     return render_view(self.context, self.request, name, secure)