Exemplo n.º 1
0
 def tidy_value(cls, value):
     # objeto exposto
     if isinstance(value, ExposedObject):
         name = getattr(value, 'nome', getattr(value, 'descricao', False))
         ref = cls.tidy_label(value.__class__.__name__) + \
             (" %s" % unicode(value.id)) + \
             (u"" if not name else (u": %s" % name))
         uri = getattr(value, 'uri', False)
         return link_to_if(uri, ref, uri)
     # listas
     elif isinstance(value, Iterable) and \
             not isinstance(value, basestring) and \
             not isinstance(value, dict):
         return ul(cls.tidy_value(item) for item in value)
     # dicionarios
     elif isinstance(value, dict):
         return HTML.dl(HTML(*[
             HTML(*[HTML.dt(cls.tidy_label(k)), HTML.dd(cls.tidy_value(v))])
                 for k, v in value.items()]
         ))
     # datas
     elif isinstance(value, date):
         return value.strftime(u"%d/%m/%Y")
     # decimais (em geral, valores moeda)
     elif isinstance(value, Decimal):
         return u"R$ "+locale.format(u"%.02f",value, grouping=True, monetary=True)
     # booleanos
     elif isinstance(value, bool):
         return u"Verdadeiro" if value else u"Falso"
     # strings longas
     elif isinstance(value, unicode) and len(value) > 140:
         return format_paragraphs(value, preserve_lines=True)
     # caso geral
     else:
         uri = getattr(value, 'uri', False)
         return link_to_if(uri, value, uri)
Exemplo n.º 2
0
    def parse_cornice_service(self, url, serv, path_stats=None):
        """
        Parses a cornice service definition and returns a dict with information
        about the service:

        Parameters

        - url       ::: url route of the service
        - service   ::: cornice service

        Output:

        a dict with thefollowing structure:

        - url       ::: url route of the service
        - methods   ::: dict with service defined methods as keys and a dict
                        with the following structure as values:

                        - callable  ::: view python callable object
                        - code      ::: callable source code prettified and
                                        converted to html friendly syntax with
                                        pygments
                        - docstring ::: callable docstring
                        - calls     ::: list that contains tracked calls for
                                        that specific METHOD and URL
        """
        #url = serv.path
        nurl = self.normalize_url(url)

        if self.take_path(url):

            # load any previously saved stats for this route or initialize
            # a new stats dictionary
            if not path_stats:
                path_stats = self.storage.load(nurl)

            if not 'url' in path_stats:
                path_stats['url'] = url

            if not 'methods' in path_stats:
                path_stats['methods'] = {}
                path_stats['methods_with_stats'] = []

            psts = path_stats['methods']
            for (method, view, args) in serv.definitions:
                foo = getattr(args['klass'], view)

                try:
                    docstring = converters.format_paragraphs(
                        inspect.getdoc(foo), True)
                except:
                    docstring = ''

                try:
                    source = inspect.getsource(foo)
                    source = highlight(source, PythonLexer(), HtmlFormatter())

                except:
                    source = ''

                psts_meth = psts.get(method, {'calls': []})

                psts_meth.update({
                    'docstring': docstring,
                    'callable': '%s.%s' % (args['klass'], view),
                    'code': source
                })
                psts[method] = psts_meth

            self.storage.save(nurl, path_stats)

            # Add the path to the current global live stats
            self.stats[nurl] = path_stats
Exemplo n.º 3
0
    def load_route(self, route):
        path = route['introspectable']['pattern']

        if self.take_path(path):

            # normalized path used to save the eventual route json (if the
            # configured storage don't support some url chars (like '/' for
            # JsonStorages
            npath = self.normalize_url(path)

            if npath not in self.stats:

                # load any previously saved stats for this route or initialize
                # a new stats dictionary
                path_stats = self.storage.load(npath)

                # it url is not registered for this routes it means it's the
                # the first time we register it. So we need to configure it's
                # url and save it for the next time
                if not 'url' in path_stats:
                    path_stats['url'] = path

                if not 'methods' in path_stats:
                    path_stats['methods'] = {}
                    path_stats['methods_with_stats'] = []

                for rel in route['related']:
                    foo = rel['callable']
                    docstring = converters.format_paragraphs(
                        inspect.getdoc(foo), True)

                    try:
                        source = inspect.getsource(foo)
                        source = highlight(source, PythonLexer(),
                                           HtmlFormatter())
                    except TypeError:
                        source = ''

                    if rel['request_methods']:
                        path_stats['methods'][rel['request_methods']] = {
                            'code': source,
                            'docstring': docstring,
                            'callable': foo.__name__,
                            'calls': []
                        }

                    elif len(route['related']) == 1:
                        # in this case there's no specific method specified
                        # on this related. We can assume that this related
                        # view is used for all verbs

                        path_stats['methods']['ALL'] = {
                            'code': source,
                            'docstring': docstring,
                            'callable': foo.__name__,
                            'calls': []
                        }

                self.storage.save(npath, path_stats)

                # Add the path to the current global live stats
                self.stats[npath] = path_stats
Exemplo n.º 4
0
def test_format_paragraphs6():
    eq_(u"<p>A paragraph\n With a newline</p>",
        format_paragraphs("A paragraph\n With a newline"))
Exemplo n.º 5
0
def test_format_paragraphs7():
    eq_(u"", format_paragraphs(None))
Exemplo n.º 6
0
def test_format_paragraphs4():
    eq_(u"<p>A paragraph<br />\n With a newline</p>",
        format_paragraphs("A paragraph\n With a newline", True))
Exemplo n.º 7
0
def test_format_paragraphs5():
    eq_(u"<p>A paragraph\n With a newline</p>",
        format_paragraphs("A paragraph\n With a newline", False))
Exemplo n.º 8
0
def test_format_paragraphs3():
    eq_(u"<p>A paragraph</p>\n\n<p>and another one!</p>",
        format_paragraphs("A paragraph\n\nand another one!"))
Exemplo n.º 9
0
def test_format_paragraphs2():
    eq_(u"<p>crazy<br />\n cross<br />\n platform linebreaks</p>",
        format_paragraphs("crazy\r\n cross\r platform linebreaks", True))
Exemplo n.º 10
0
def test_format_paragraphs1():
    eq_(u"<p>crazy\n cross\n platform linebreaks</p>",
        format_paragraphs("crazy\r\n cross\r platform linebreaks"))
Exemplo n.º 11
0
    def load_route(self, route):
        path = route['introspectable']['pattern']

        if self.take_path(path):

            # normalized path used to save the eventual route json (if the
            # configured storage don't support some url chars (like '/' for
            # JsonStorages
            npath = self.normalize_url(path)

            if npath not in self.stats:

                # load any previously saved stats for this route or initialize
                # a new stats dictionary
                path_stats = self.storage.load(npath)

                # it url is not registered for this routes it means it's the
                # the first time we register it. So we need to configure it's
                # url and save it for the next time
                if not 'url' in path_stats:
                    path_stats['url'] = path

                if not 'methods' in path_stats:
                    path_stats['methods'] = {}
                    path_stats['methods_with_stats'] = []

                for rel in route['related']:
                    foo = rel['callable']
                    docstring = converters.format_paragraphs(
                        inspect.getdoc(foo), True
                    )

                    try:
                        source = inspect.getsource(foo)
                        source = highlight(source, PythonLexer(), HtmlFormatter())
                    except TypeError:
                        source = ''

                    if rel['request_methods']:
                        path_stats['methods'][rel['request_methods']] = {
                            'code': source,
                            'docstring': docstring,
                            'callable': foo.__name__,
                            'calls': []
                        }

                    elif len(route['related']) == 1:
                        # in this case there's no specific method specified
                        # on this related. We can assume that this related
                        # view is used for all verbs

                        path_stats['methods']['ALL'] = {
                            'code': source,
                            'docstring': docstring,
                            'callable': foo.__name__,
                            'calls': []
                        }

                self.storage.save(npath, path_stats)

                # Add the path to the current global live stats
                self.stats[npath] = path_stats
Exemplo n.º 12
0
    def parse_cornice_service(self, url, serv, path_stats = None):
        """
        Parses a cornice service definition and returns a dict with information
        about the service:

        Parameters

        - url       ::: url route of the service
        - service   ::: cornice service

        Output:

        a dict with thefollowing structure:

        - url       ::: url route of the service
        - methods   ::: dict with service defined methods as keys and a dict
                        with the following structure as values:

                        - callable  ::: view python callable object
                        - code      ::: callable source code prettified and
                                        converted to html friendly syntax with
                                        pygments
                        - docstring ::: callable docstring
                        - calls     ::: list that contains tracked calls for
                                        that specific METHOD and URL
        """
        #url = serv.path
        nurl = self.normalize_url(url)

        if self.take_path(url):

            # load any previously saved stats for this route or initialize
            # a new stats dictionary
            if not path_stats:
                path_stats = self.storage.load(nurl)

            if not 'url' in path_stats:
                path_stats['url'] = url

            if not 'methods' in path_stats:
                path_stats['methods'] = {}
                path_stats['methods_with_stats'] = []

            psts = path_stats['methods']
            for (method, view, args) in serv.definitions:
                foo = getattr(args['klass'], view)

                try:
                    docstring = converters.format_paragraphs(
                                inspect.getdoc(foo), True
                            )
                except:
                    docstring = ''

                try:
                    source = inspect.getsource(foo)
                    source = highlight(source, PythonLexer(), HtmlFormatter())

                except:
                    source = ''

                psts_meth = psts.get(method, {'calls': []})

                psts_meth.update({
                    'docstring': docstring,
                    'callable': '%s.%s' % (args['klass'], view),
                    'code': source
                })
                psts[method] = psts_meth

            self.storage.save(nurl, path_stats)

            # Add the path to the current global live stats
            self.stats[nurl] = path_stats