Ejemplo n.º 1
0
class Breadcrumbs(object):
    '''A lazy class for building a site breadcrumb trail to keep track
of current request location. It renders as a ``ul`` element
with class name defaulted to ``"breadcrumbs"``.
    '''
    def __init__(self,
                 min_length=2,
                 divider=None,
                 cn=None,
                 render_empty=True,
                 tag='div'):
        divider = divider or '›'
        self.divider = "<span class='divider'>" + divider + "</span>"
        self.min_length = min_length
        self.render_empty = render_empty
        self.widget = Widget(tag, cn=cn or classes.breadcrumbs)

    def items(self, request):
        crumbs = []
        while request:
            crumbs.append(request)
            request = request.parent

        cutoff = self.min_length - 1
        if cutoff:
            crumbs = crumbs[:-cutoff]

        position = len(crumbs)
        for request in crumbs:
            li = Widget('li', cn='position{0}'.format(position))
            name = request.view.breadcrumb(request)
            if position < len(crumbs):
                url = request.url
                title = request.title
                a = Widget('a', name, title=title, href=url)
                li.add(a)
                li.add(self.divider)
            else:
                li.add(name)
            position -= 1
            yield li

    def render(self, request):
        if request.valid:
            ul = Widget('ul')
            for li in reversed(tuple(self.items(request))):
                ul.add(li)
            if ul:
                self.widget.add(ul)
                return self.widget.render(request)
        if self.render_empty:
            return NON_BREACKING_SPACE
        else:
            return ''
Ejemplo n.º 2
0
 def render(self, request):
     if request.valid:
         ul = Widget("ul")
         for li in reversed(tuple(self.items(request))):
             ul.add(li)
         if ul:
             self.widget.add(ul)
             return self.widget.render(request)
     if self.render_empty:
         return NON_BREACKING_SPACE
     else:
         return ""
Ejemplo n.º 3
0
 def render(self, request):
     if request.valid:
         ul = Widget('ul')
         for li in reversed(tuple(self.items(request))):
             ul.add(li)
         if ul:
             self.widget.add(ul)
             return self.widget.render(request)
     if self.render_empty:
         return NON_BREACKING_SPACE
     else:
         return ''
Ejemplo n.º 4
0
class Breadcrumbs(object):
    """A lazy class for building a site breadcrumb trail to keep track
of current request location. It renders as a ``ul`` element
with class name defaulted to ``"breadcrumbs"``.
    """

    def __init__(self, min_length=2, divider=None, cn=None, render_empty=True, tag="div"):
        divider = divider or "&rsaquo;"
        self.divider = "<span class='divider'>" + divider + "</span>"
        self.min_length = min_length
        self.render_empty = render_empty
        self.widget = Widget(tag, cn=cn or classes.breadcrumbs)

    def items(self, request):
        crumbs = []
        while request:
            crumbs.append(request)
            request = request.parent

        cutoff = self.min_length - 1
        if cutoff:
            crumbs = crumbs[:-cutoff]

        position = len(crumbs)
        for request in crumbs:
            li = Widget("li", cn="position{0}".format(position))
            name = request.view.breadcrumb(request)
            if position < len(crumbs):
                url = request.url
                title = request.title
                a = Widget("a", name, title=title, href=url)
                li.add(a)
                li.add(self.divider)
            else:
                li.add(name)
            position -= 1
            yield li

    def render(self, request):
        if request.valid:
            ul = Widget("ul")
            for li in reversed(tuple(self.items(request))):
                ul.add(li)
            if ul:
                self.widget.add(ul)
                return self.widget.render(request)
        if self.render_empty:
            return NON_BREACKING_SPACE
        else:
            return ""
Ejemplo n.º 5
0
 def render_instance_default(self, request, instance, **kwargs):
     mkp = markups.get(instance.markup)
     text = instance.body
     if mkp:
         text = mkp(request, text)
     w = Widget('div', text, cn=classes.sitecontent)
     if instance.javascript:
         g = script_template % instance.javascript
         script = g.replace('\r\n', '\n')
         if request.is_xhr:
             w.add(script)
         else:
             request.media.add(media.Media(js=[script]))
     return w.render(request)
Ejemplo n.º 6
0
 def render_instance_default(self, request, instance, **kwargs):
     mkp = markups.get(instance.markup)
     text = instance.body
     if mkp:
         text = mkp(request, text)
     w = Widget('div', text, cn=classes.sitecontent)
     if instance.javascript:
         g = script_template % instance.javascript
         script = g.replace('\r\n','\n')
         if request.is_xhr:
             w.add(script)
         else:
             request.media.add(media.Media(js=[script]))
     return w.render(request)
Ejemplo n.º 7
0
def navstream(request, urlselects, secondary_after, level):
    for request, nav in sorted(((c, c.in_navigation) for c in request.auth_children()), key=lambda x: x[1]):
        if not nav:
            continue
        link = application_link(request, asbutton=False)
        li = Widget("li", link)
        secondary = secondary_after and nav > secondary_after
        if link.attrs["href"] in urlselects:
            li.addClass(classes.state_active)
        if level:
            slis = list(navstream(request, urlselects, None, level - 1))
            if slis:
                ul = Widget("ul")
                for sli, _ in slis:
                    ul.add(sli)
                li.add(ul)
        yield li, secondary
Ejemplo n.º 8
0
def navstream(request, urlselects, secondary_after, level):
    for request, nav in sorted(((c, c.in_navigation)\
                for c in request.auth_children()), key=lambda x : x[1]):
        if not nav:
            continue
        link = application_link(request, asbutton=False)
        li = Widget('li', link)
        secondary = secondary_after and nav > secondary_after
        if link.attrs['href'] in urlselects:
            li.addClass(classes.state_active)
        if level:
            slis = list(navstream(request, urlselects, None, level - 1))
            if slis:
                ul = Widget('ul')
                for sli, _ in slis:
                    ul.add(sli)
                li.add(ul)
        yield li, secondary
Ejemplo n.º 9
0
def profile(request, callback, Response):
    tmp = tempfile.mktemp()
    out = Stream()
    prof = profiler.Profile()
    response = prof.runcall(callback)
    prof.dump_stats(tmp)
    stats = pstats.Stats(tmp, stream=out)
    #stats.strip_dirs()          # Must happen prior to sort_stats
    stats.sort_stats('time', 'calls')
    stats.print_stats()
    stats_str = out.getvalue()
    os.unlink(tmp)
    stats_str = stats_str.split('\n')
    headers = '\n'.join(make_header(stats_str[:4]))
    data = data_stream(stats_str[6:],100)
    tables = make_stat_table(request, data)
    w = Widget(cn = 'profiler')
    w.add(Widget('div', headers, cn = 'legend'))
    w.add(tabs(tables))
    content = w.render(request)
    return to_bytes('\n'.join(html_doc_stream(request, content, 200)))
Ejemplo n.º 10
0
def profile(request, callback, Response):
    tmp = tempfile.mktemp()
    out = Stream()
    prof = profiler.Profile()
    response = prof.runcall(callback)
    prof.dump_stats(tmp)
    stats = pstats.Stats(tmp, stream=out)
    #stats.strip_dirs()          # Must happen prior to sort_stats
    stats.sort_stats('time', 'calls')
    stats.print_stats()
    stats_str = out.getvalue()
    os.unlink(tmp)
    stats_str = stats_str.split('\n')
    headers = '\n'.join(make_header(stats_str[:4]))
    data = data_stream(stats_str[6:], 100)
    tables = make_stat_table(request, data)
    w = Widget(cn='profiler')
    w.add(Widget('div', headers, cn='legend'))
    w.add(tabs(tables))
    content = w.render(request)
    return to_bytes('\n'.join(html_doc_stream(request, content, 200)))
Ejemplo n.º 11
0
    def items(self, request):
        crumbs = []
        while request:
            crumbs.append(request)
            request = request.parent

        cutoff = self.min_length - 1
        if cutoff:
            crumbs = crumbs[:-cutoff]

        position = len(crumbs)
        for request in crumbs:
            li = Widget("li", cn="position{0}".format(position))
            name = request.view.breadcrumb(request)
            if position < len(crumbs):
                url = request.url
                title = request.title
                a = Widget("a", name, title=title, href=url)
                li.add(a)
                li.add(self.divider)
            else:
                li.add(name)
            position -= 1
            yield li
Ejemplo n.º 12
0
    def items(self, request):
        crumbs = []
        while request:
            crumbs.append(request)
            request = request.parent

        cutoff = self.min_length - 1
        if cutoff:
            crumbs = crumbs[:-cutoff]

        position = len(crumbs)
        for request in crumbs:
            li = Widget('li', cn='position{0}'.format(position))
            name = request.view.breadcrumb(request)
            if position < len(crumbs):
                url = request.url
                title = request.title
                a = Widget('a', name, title=title, href=url)
                li.add(a)
                li.add(self.divider)
            else:
                li.add(name)
            position -= 1
            yield li
Ejemplo n.º 13
0
    def handle_error(self, request, response):
        '''Render an error into text or Html depending on *content_type*.
This function can be overwritten by user implementation.'''
        exc_info = request.exc_info
        settings = request.settings
        status = 500
        if exc_info and exc_info[0] is not None:
            status = getattr(exc_info[1], 'status', status)
        else:
            exc_info = None
        # 302 is a special case, we redirect
        content_type = request.content_type
        if status in REDIRECT_CODES:
            location = dict(exc_info[1].headers)['location']
            if request.is_xhr:
                content = ajax.jredirect(request.environ, location)
            else:
                content_type = None
                response.headers['Location'] = iri_to_uri(location)
                content = ''
        else:
            err_cls = '%s%s' % (classes.error, status)
            err_title = '%s %s' % (status, error_title(status))
            if content_type == 'text/plain':
                content = err_title
                if settings.DEBUG:
                    content += '\n\n' + html_trace(exc_info, plain=True)
            else:
                inner = Widget('div', cn=(classes.error, err_cls))
                if settings.DEBUG:
                    inner.addClass('debug')
                    inner.add(Widget('h2', err_title))
                    inner.add(Widget('a', request.path, href=request.path))
                    inner.add(html_trace(exc_info))
                else:
                    func_name = 'render_error_%s' % status
                    if hasattr(self, func_name):
                        text = getattr(self, func_name)(request, status)
                    else:
                        text = error_title
                    inner.add(text)
                if request.is_xhr:
                    content = ajax.jservererror(request.environ,
                                                inner.render(request))
                else:
                    try:
                        layout = request.view.root.get_page_layout(err_cls,
                                                                   classes.error,
                                                                   'default')
                        outer = layout()
                        content = outer.render(request,
                                               context={'content': inner})
                    except:
                        logger.error('Could not render %s error on %s layout',
                                     status, layout, exc_info=True)
                        content = inner.render(request)
        if is_renderer(content):
            response.status_code = 200
            response.content_type = content.content_type()
            content = content.render(request)
        else:
            response.content_type = content_type
            response.status_code = status
        if status == 500:
            logger.critical('Interval server error', exc_info=exc_info)
        return content
Ejemplo n.º 14
0
    def handle_error(self, request, response):
        '''Render an error into text or Html depending on *content_type*.
This function can be overwritten by user implementation.'''
        exc_info = request.exc_info
        settings = request.settings
        status = 500
        if exc_info and exc_info[0] is not None:
            status = getattr(exc_info[1], 'status', status)
        else:
            exc_info = None
        # 302 is a special case, we redirect
        content_type = request.content_type
        if status in REDIRECT_CODES:
            location = dict(exc_info[1].headers)['location']
            if request.is_xhr:
                content = ajax.jredirect(request.environ, location)
            else:
                content_type = None
                response.headers['Location'] = iri_to_uri(location)
                content = ''
        else:
            err_cls = '%s%s' % (classes.error, status)
            err_title = '%s %s' % (status, error_title(status))
            if content_type == 'text/plain':
                content = err_title
                if settings.DEBUG:
                    content += '\n\n' + html_trace(exc_info, plain=True)
            else:
                inner = Widget('div', cn=(classes.error, err_cls))
                if settings.DEBUG:
                    inner.addClass('debug')
                    inner.add(Widget('h2', err_title))
                    inner.add(Widget('a', request.path, href=request.path))
                    inner.add(html_trace(exc_info))
                else:
                    func_name = 'render_error_%s' % status
                    if hasattr(self, func_name):
                        text = getattr(self, func_name)(request, status)
                    else:
                        text = error_title
                    inner.add(text)
                if request.is_xhr:
                    content = ajax.jservererror(request.environ,
                                                inner.render(request))
                else:
                    try:
                        layout = request.view.root.get_page_layout(
                            err_cls, classes.error, 'default')
                        outer = layout()
                        content = outer.render(request,
                                               context={'content': inner})
                    except:
                        logger.error('Could not render %s error on %s layout',
                                     status,
                                     layout,
                                     exc_info=True)
                        content = inner.render(request)
        if is_renderer(content):
            response.status_code = 200
            response.content_type = content.content_type()
            content = content.render(request)
        else:
            response.content_type = content_type
            response.status_code = status
        if status == 500:
            logger.critical('Interval server error', exc_info=exc_info)
        return content