コード例 #1
0
ファイル: test_html.py プロジェクト: amrX2K/web2py
 def test_truncate_string(self):
     # Ascii text
     self.assertEqual(truncate_string('Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
                                      'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
                                      length=30), 'Lorem ipsum dolor sit amet,...')
     # French text
     self.assertEqual(truncate_string('Un texte en français avec des accents et des caractères bizarre.', length=30),
                      'Un texte en français avec d...')
コード例 #2
0
ファイル: test_html.py プロジェクト: topleft/book2-exercises
 def test_truncate_string(self):
     # Ascii text
     self.assertEqual(
         truncate_string(
             "Lorem ipsum dolor sit amet, consectetur adipiscing elit, "
             "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
             length=30,
         ),
         "Lorem ipsum dolor sit amet,...",
     )
     self.assertEqual(
         truncate_string("Short text shorter than the length parameter.", length=100),
         "Short text shorter than the length parameter.",
     )
     # French text
     self.assertEqual(
         truncate_string("Un texte en français avec des accents et des caractères bizarre.", length=30),
         "Un texte en français avec d...",
     )
コード例 #3
0
    def render_table(self, 
              sqlrows,
              linkto=None,
              upload=None,
              orderby=True,
              headers={},
              truncate=16,
              th_link = '',
              columns=None,
              extracolumns=None,
              selectid=None,
              renderstyle=False,
              cid=None,
              **attributes):
        
        request = current.request
        
        attributes['_class'] = "table table-striped table-bordered table-condensed"
        if th_link == '':
            th_link=URL(self.ctrl, self.method)
            
        row = []    
        if not sqlrows:
            return DIV('', _class='web2py_table')
        if not columns:
            columns = sqlrows.colnames
        else:
            cols = columns[:]
            columns = []
            for c in cols:
                columns.append(str(c))
        if headers=='fieldname:capitalize':
            headers = {}
            for c in columns:
                headers[c] = c.split('.')[-1].replace('_',' ').title()
        elif headers=='labels':
            headers = {}
            for c in columns:
                if c.find('(') > -1:
                    headers[c] = c
                else:
                    (t,f) = c.split('.')
                    field = sqlrows.db[t][f]
                    headers[c] = field.label
        if headers is None:
            headers = {}
        else:
            for c in columns:#new implement dict
                if isinstance(headers.get(c, c), dict):
                    coldict = headers.get(c, c)
                    attrcol = dict()
                    if coldict['width']!="":
                        attrcol.update(_width=coldict['width'])
                    if coldict['class']!="":
                        attrcol.update(_class=coldict['class'])
                    row.append(TH(coldict['label'],**attrcol))
                elif orderby:
                    if self.next_orderby.split('~')[-1] == c:
                        u = self.next_orderby
                    else:
                        u = c
                    _href = th_link+'?orderby=' + u
                    if self.search_string != '':
                        _href = _href + '&search_string=' + self.search_string
                        
                    row.append(TH(A(headers.get(c, c), _href=_href, cid=cid)))
                else:
                    row.append(TH(headers.get(c, c)))
    
            if extracolumns:#new implement dict
                for c in extracolumns:
                    attrcol = dict()
                    if c['width']!="":
                        attrcol.update(_width=c['width'])
                    if c['class']!="":
                        attrcol.update(_class=c['class'])
                    row.append(TH(c['label'],**attrcol))
        
        thead = THEAD(TR(*row, _class=''))
        table = TABLE(thead, **attributes)
        
        tbody = []
        for (rc, record) in enumerate(sqlrows):
            row = []

            if not selectid is None: #new implement
                if record.get('id') == selectid:
                    _class += ' rowselected'

            for colname in columns:
                if not table_field.match(colname):
                    if "_extra" in record and colname in record._extra:
                        r = record._extra[colname]
                        row.append(TD(r))
                        continue
                    else:
                        raise KeyError("Column %s not found (SQLTABLE)" % colname)
                (tablename, fieldname) = colname.split('.')
                try:
                    field = sqlrows.db[tablename][fieldname]
                except KeyError:
                    field = None
                if tablename in record \
                        and isinstance(record, Row) \
                        and isinstance(record[tablename],Row):
                    r = record[tablename][fieldname]
                elif fieldname in record:
                    r = record[fieldname]
                else:
                    raise SyntaxError, 'something wrong in Rows object'
                r_old = r
                if not field:
                    pass
                elif linkto and field.type == 'id':
                    try:
                        href = linkto(r, 'table', tablename)
                    except TypeError:
                        href = '%s/%s/%s' % (linkto, tablename, r_old)
                    r = A(r, _href=href)
                elif isinstance(field.type, str) and field.type.startswith('reference'):
                    if linkto:
                        ref = field.type[10:]
                        try:
                            href = linkto(r, 'reference', ref)
                        except TypeError:
                            href = '%s/%s/%s' % (linkto, ref, r_old)
                            if ref.find('.') >= 0:
                                tref,fref = ref.split('.')
                                if hasattr(sqlrows.db[tref],'_primarykey'):
                                    href = '%s/%s?%s' % (linkto, tref, urllib.urlencode({fref:r}))
                        r = A(represent(field,r,record), _href=str(href))
                    elif field.represent:
                        r = represent(field,r,record)
                elif linkto and hasattr(field._table,'_primarykey')\
                        and fieldname in field._table._primarykey:
                    # have to test this with multi-key tables
                    key = urllib.urlencode(dict( [ \
                                ((tablename in record \
                                      and isinstance(record, Row) \
                                      and isinstance(record[tablename], Row)) and
                                 (k, record[tablename][k])) or (k, record[k]) \
                                    for k in field._table._primarykey ] ))
                    r = A(r, _href='%s/%s?%s' % (linkto, tablename, key))
                elif isinstance(field.type, str) and field.type.startswith('list:'):
                    r = represent(field,r or [],record)
                elif field.represent:
                    r = represent(field,r,record)
                elif field.type == 'blob' and r:
                    r = 'DATA'
                elif field.type == 'boolean':
                    r = INPUT(_type='checkbox', value=r, _disabled='')                   
                elif field.type == 'upload':
                    if upload and r:
                        r = A(current.T('file'), _href='%s/%s' % (upload, r))
                    elif r:
                        r = current.T('file')
                    else:
                        r = ''
                elif field.type in ['string','text']:
                    r = str(field.formatter(r))
                    if headers!={}: #new implement dict
                        if isinstance(headers[colname],dict):
                            if isinstance(headers[colname]['truncate'], int):
                                r = truncate_string(r, headers[colname]['truncate'])
                    elif not truncate is None:
                        r = truncate_string(r, truncate)
                attrcol = dict()#new implement dict
                if headers!={}:
                    if isinstance(headers[colname],dict):
                        colclass=headers[colname]['class']
                        if headers[colname]['selected']:
                            colclass= str(headers[colname]['class'] + " colselected").strip()
                        if colclass!="":
                            attrcol.update(_class=colclass)

                row.append(TD(r,**attrcol))

            if extracolumns:#new implement dict
                for c in extracolumns:
                    attrcol = dict()
                    colclass=c['class']
                    if c['selected']:
                        colclass= str(c['class'] + " colselected").strip()
                    if colclass!="":
                        attrcol.update(_class=colclass)
                    contentfunc = c['content']
                    row.append(TD(contentfunc(record, rc),**attrcol))
                
            if self.show_function:
                tbody.append(TR(*row, 
                                _id='%s_%s_row_%d' % (self.ctrl, self.method, record[self.field_id]),
                                _onclick='getData("%(grid_id)s", "%(url)s", %(value)s, %(detail)s); return false;' %
                                {'grid_id': self.grid_id, 
                                 'url': URL(r=request, f=self.show_function, extension='load'),
                                 'value': str(record[self.field_id]),
                                 'detail': 'true'}
                            ))
            else:
                tbody.append(TR(*row, _id='%s_%s_row_%d' % (self.ctrl, self.method, record[self.field_id])))
        table.append(TBODY(*tbody))        

        return DIV(table, _class='web2py_table')
コード例 #4
0
    def render_table(
        self,
        sqlrows,
        linkto=None,
        upload=None,
        orderby=True,
        headers={},
        truncate=16,
        th_link="",
        columns=None,
        extracolumns=None,
        selectid=None,
        renderstyle=False,
        cid=None,
        **attributes
    ):
        attributes["_class"] = "table table-striped table-bordered table-condensed"
        if th_link == "":
            th_link = URL(self.ctrl, self.method)

        row = []
        if not sqlrows:
            return DIV("", _class="web2py_table")
        if not columns:
            columns = sqlrows.colnames
        else:
            cols = columns[:]
            columns = []
            for c in cols:
                columns.append(str(c))
        if headers == "fieldname:capitalize":
            headers = {}
            for c in columns:
                headers[c] = c.split(".")[-1].replace("_", " ").title()
        elif headers == "labels":
            headers = {}
            for c in columns:
                if c.find("(") > -1:
                    headers[c] = c
                else:
                    (t, f) = c.split(".")
                    field = sqlrows.db[t][f]
                    headers[c] = field.label
        if headers is None:
            headers = {}
        else:
            for c in columns:  # new implement dict
                if isinstance(headers.get(c, c), dict):
                    coldict = headers.get(c, c)
                    attrcol = dict()
                    if coldict["width"] != "":
                        attrcol.update(_width=coldict["width"])
                    if coldict["class"] != "":
                        attrcol.update(_class=coldict["class"])
                    row.append(TH(coldict["label"], **attrcol))
                elif orderby:
                    if self.next_orderby.split("~")[-1] == c:
                        u = self.next_orderby
                    else:
                        u = c
                    _href = th_link + "?orderby=" + u
                    if self.search_string != "":
                        _href = _href + "&search_string=" + self.search_string

                    row.append(TH(A(headers.get(c, c), _href=_href, cid=cid)))
                else:
                    row.append(TH(headers.get(c, c)))

            if extracolumns:  # new implement dict
                for c in extracolumns:
                    attrcol = dict()
                    if c["width"] != "":
                        attrcol.update(_width=c["width"])
                    if c["class"] != "":
                        attrcol.update(_class=c["class"])
                    row.append(TH(c["label"], **attrcol))

        thead = THEAD(TR(*row, _class=""))
        table = TABLE(thead, **attributes)

        tbody = []
        for (rc, record) in enumerate(sqlrows):
            row = []

            if not selectid is None:  # new implement
                if record.get("id") == selectid:
                    _class += " rowselected"

            for colname in columns:
                if not table_field.match(colname):
                    if "_extra" in record and colname in record._extra:
                        r = record._extra[colname]
                        row.append(TD(r))
                        continue
                    else:
                        raise KeyError("Column %s not found (SQLTABLE)" % colname)
                (tablename, fieldname) = colname.split(".")
                try:
                    field = sqlrows.db[tablename][fieldname]
                except KeyError:
                    field = None
                if tablename in record and isinstance(record, Row) and isinstance(record[tablename], Row):
                    r = record[tablename][fieldname]
                elif fieldname in record:
                    r = record[fieldname]
                else:
                    raise SyntaxError, "something wrong in Rows object"
                r_old = r
                if not field:
                    pass
                elif linkto and field.type == "id":
                    try:
                        href = linkto(r, "table", tablename)
                    except TypeError:
                        href = "%s/%s/%s" % (linkto, tablename, r_old)
                    r = A(r, _href=href)
                elif isinstance(field.type, str) and field.type.startswith("reference"):
                    if linkto:
                        ref = field.type[10:]
                        try:
                            href = linkto(r, "reference", ref)
                        except TypeError:
                            href = "%s/%s/%s" % (linkto, ref, r_old)
                            if ref.find(".") >= 0:
                                tref, fref = ref.split(".")
                                if hasattr(sqlrows.db[tref], "_primarykey"):
                                    href = "%s/%s?%s" % (linkto, tref, urllib.urlencode({fref: r}))
                        r = A(represent(field, r, record), _href=str(href))
                    elif field.represent:
                        r = represent(field, r, record)
                elif linkto and hasattr(field._table, "_primarykey") and fieldname in field._table._primarykey:
                    # have to test this with multi-key tables
                    key = urllib.urlencode(
                        dict(
                            [
                                (
                                    (
                                        tablename in record
                                        and isinstance(record, Row)
                                        and isinstance(record[tablename], Row)
                                    )
                                    and (k, record[tablename][k])
                                )
                                or (k, record[k])
                                for k in field._table._primarykey
                            ]
                        )
                    )
                    r = A(r, _href="%s/%s?%s" % (linkto, tablename, key))
                elif isinstance(field.type, str) and field.type.startswith("list:"):
                    r = represent(field, r or [], record)
                elif field.represent:
                    r = represent(field, r, record)
                elif field.type == "blob" and r:
                    r = "DATA"
                elif field.type == "boolean":
                    r = INPUT(_type="checkbox", value=r, _disabled="")
                elif field.type == "upload":
                    if upload and r:
                        r = A(current.T("file"), _href="%s/%s" % (upload, r))
                    elif r:
                        r = current.T("file")
                    else:
                        r = ""
                elif field.type in ["string", "text"]:
                    r = str(field.formatter(r))
                    if headers != {}:  # new implement dict
                        if isinstance(headers[colname], dict):
                            if isinstance(headers[colname]["truncate"], int):
                                r = truncate_string(r, headers[colname]["truncate"])
                    elif not truncate is None:
                        r = truncate_string(r, truncate)
                attrcol = dict()  # new implement dict
                if headers != {}:
                    if isinstance(headers[colname], dict):
                        colclass = headers[colname]["class"]
                        if headers[colname]["selected"]:
                            colclass = str(headers[colname]["class"] + " colselected").strip()
                        if colclass != "":
                            attrcol.update(_class=colclass)

                row.append(TD(r, **attrcol))

            if extracolumns:  # new implement dict
                for c in extracolumns:
                    attrcol = dict()
                    colclass = c["class"]
                    if c["selected"]:
                        colclass = str(c["class"] + " colselected").strip()
                    if colclass != "":
                        attrcol.update(_class=colclass)
                    contentfunc = c["content"]
                    row.append(TD(contentfunc(record, rc), **attrcol))

            tbody.append(TR(*row))
        table.append(TBODY(*tbody))

        return DIV(table, _class="web2py_table")
コード例 #5
0
    def render_table(self, 
              sqlrows,
              linkto=None,
              upload=None,
              orderby=True,
              headers={},
              truncate=16,
              th_link = '',
              columns=None,
              extracolumns=None,
              selectid=None,
              renderstyle=False,
              cid=None,
              **attributes):
        attributes['_class'] = "table table-striped table-bordered table-condensed"
        if th_link == '':
            th_link=URL(self.ctrl, self.method)
            
        row = []    
        if not sqlrows:
            return DIV('', _class='web2py_table')
        if not columns:
            columns = sqlrows.colnames
        else:
            cols = columns[:]
            columns = []
            for c in cols:
                columns.append(str(c))
        if headers=='fieldname:capitalize':
            headers = {}
            for c in columns:
                headers[c] = c.split('.')[-1].replace('_',' ').title()
        elif headers=='labels':
            headers = {}
            for c in columns:
                if c.find('(') > -1:
                    headers[c] = c
                else:
                    (t,f) = c.split('.')
                    field = sqlrows.db[t][f]
                    headers[c] = field.label
        if headers is None:
            headers = {}
        else:
            for c in columns:#new implement dict
                if isinstance(headers.get(c, c), dict):
                    coldict = headers.get(c, c)
                    attrcol = dict()
                    if coldict['width']!="":
                        attrcol.update(_width=coldict['width'])
                    if coldict['class']!="":
                        attrcol.update(_class=coldict['class'])
                    row.append(TH(coldict['label'],**attrcol))
                elif orderby:
                    if self.next_orderby.split('~')[-1] == c:
                        u = self.next_orderby
                    else:
                        u = c
                    _href = th_link+'?orderby=' + u
                    if self.search_string != '':
                        _href = _href + '&search_string=' + self.search_string
                        
                    row.append(TH(A(headers.get(c, c), _href=_href, cid=cid)))
                else:
                    row.append(TH(headers.get(c, c)))
    
            if extracolumns:#new implement dict
                for c in extracolumns:
                    attrcol = dict()
                    if c['width']!="":
                        attrcol.update(_width=c['width'])
                    if c['class']!="":
                        attrcol.update(_class=c['class'])
                    row.append(TH(c['label'],**attrcol))
        
        thead = THEAD(TR(*row, _class=''))
        table = TABLE(thead, **attributes)
        
        tbody = []
        for (rc, record) in enumerate(sqlrows):
            row = []

            if not selectid is None: #new implement
                if record.get('id') == selectid:
                    _class += ' rowselected'

            for colname in columns:
                if not table_field.match(colname):
                    if "_extra" in record and colname in record._extra:
                        r = record._extra[colname]
                        row.append(TD(r))
                        continue
                    else:
                        raise KeyError("Column %s not found (SQLTABLE)" % colname)
                (tablename, fieldname) = colname.split('.')
                try:
                    field = sqlrows.db[tablename][fieldname]
                except KeyError:
                    field = None
                if tablename in record \
                        and isinstance(record, Row) \
                        and isinstance(record[tablename],Row):
                    r = record[tablename][fieldname]
                elif fieldname in record:
                    r = record[fieldname]
                else:
                    raise SyntaxError, 'something wrong in Rows object'
                r_old = r
                if not field:
                    pass
                elif linkto and field.type == 'id':
                    try:
                        href = linkto(r, 'table', tablename)
                    except TypeError:
                        href = '%s/%s/%s' % (linkto, tablename, r_old)
                    r = A(r, _href=href)
                elif isinstance(field.type, str) and field.type.startswith('reference'):
                    if linkto:
                        ref = field.type[10:]
                        try:
                            href = linkto(r, 'reference', ref)
                        except TypeError:
                            href = '%s/%s/%s' % (linkto, ref, r_old)
                            if ref.find('.') >= 0:
                                tref,fref = ref.split('.')
                                if hasattr(sqlrows.db[tref],'_primarykey'):
                                    href = '%s/%s?%s' % (linkto, tref, urllib.urlencode({fref:r}))
                        r = A(represent(field,r,record), _href=str(href))
                    elif field.represent:
                        r = represent(field,r,record)
                elif linkto and hasattr(field._table,'_primarykey')\
                        and fieldname in field._table._primarykey:
                    # have to test this with multi-key tables
                    key = urllib.urlencode(dict( [ \
                                ((tablename in record \
                                      and isinstance(record, Row) \
                                      and isinstance(record[tablename], Row)) and
                                 (k, record[tablename][k])) or (k, record[k]) \
                                    for k in field._table._primarykey ] ))
                    r = A(r, _href='%s/%s?%s' % (linkto, tablename, key))
                elif isinstance(field.type, str) and field.type.startswith('list:'):
                    r = represent(field,r or [],record)
                elif field.represent:
                    r = represent(field,r,record)
                elif field.type == 'blob' and r:
                    r = 'DATA'
                elif field.type == 'boolean':
                    r = INPUT(_type='checkbox', value=r, _disabled='')                   
                elif field.type == 'upload':
                    if upload and r:
                        r = A(current.T('file'), _href='%s/%s' % (upload, r))
                    elif r:
                        r = current.T('file')
                    else:
                        r = ''
                elif field.type in ['string','text']:
                    r = str(field.formatter(r))
                    if headers!={}: #new implement dict
                        if isinstance(headers[colname],dict):
                            if isinstance(headers[colname]['truncate'], int):
                                r = truncate_string(r, headers[colname]['truncate'])
                    elif not truncate is None:
                        r = truncate_string(r, truncate)
                attrcol = dict()#new implement dict
                if headers!={}:
                    if isinstance(headers[colname],dict):
                        colclass=headers[colname]['class']
                        if headers[colname]['selected']:
                            colclass= str(headers[colname]['class'] + " colselected").strip()
                        if colclass!="":
                            attrcol.update(_class=colclass)

                row.append(TD(r,**attrcol))

            if extracolumns:#new implement dict
                for c in extracolumns:
                    attrcol = dict()
                    colclass=c['class']
                    if c['selected']:
                        colclass= str(c['class'] + " colselected").strip()
                    if colclass!="":
                        attrcol.update(_class=colclass)
                    contentfunc = c['content']
                    row.append(TD(contentfunc(record, rc),**attrcol))

            tbody.append(TR(*row))        
        table.append(TBODY(*tbody))

        return DIV(table, _class='web2py_table')