Example #1
0
 def test_markdown(self):
     def markdown(text, tag=None, attributes={}):
         r = {None: re.sub('\s+',' ',text), \
              'h1':'#'+text+'\\n\\n', \
              'p':text+'\\n'}.get(tag,text)
         return r
     a=TAG('<h1>Header</h1><p>this is a     test</p>')
     ret = a.flatten(markdown)
     self.assertEqual(ret, '#Header\\n\\nthis is a test\\n')
Example #2
0
 def test_TAG(self):
     self.assertEqual(TAG.first(TAG.second('test'), _key=3).xml(),
                      b'<first key="3"><second>test</second></first>')
     # ending in underscore "triggers" <input /> style
     self.assertEqual(TAG.first_(TAG.second('test'), _key=3).xml(),
                      b'<first key="3" />')
     # unicode test for TAG
     self.assertEqual(TAG.div(u'Texte en français avec des caractères accentués...').xml(),
                      b'<div>Texte en fran\xc3\xa7ais avec des caract\xc3\xa8res accentu\xc3\xa9s...</div>')
Example #3
0
 def test_TAG(self):
     self.assertEqual(TAG.first(TAG.second('test'), _key=3).xml(),
                      b'<first key="3"><second>test</second></first>')
     # ending in underscore "triggers" <input /> style
     self.assertEqual(TAG.first_(TAG.second('test'), _key=3).xml(),
                      b'<first key="3" />')
     # unicode test for TAG
     self.assertEqual(TAG.div(u'Texte en français avec des caractères accentués...').xml(),
                      b'<div>Texte en fran\xc3\xa7ais avec des caract\xc3\xa8res accentu\xc3\xa9s...</div>')
Example #4
0
 def test_markdown(self):
     def markdown(text, tag=None, attributes={}):
         r = {None: re.sub('\s+',' ',text), \
              'h1':'#'+text+'\\n\\n', \
              'p':text+'\\n'}.get(tag,text)
         return r
     a=TAG('<h1>Header</h1><p>this is a     test</p>')
     ret = a.flatten(markdown)
     self.assertEqual(ret, '#Header\\n\\nthis is a test\\n')
Example #5
0
def html_to_markmin(html):
    """Replace HTML with Markmin"""

    if html is None:
        return ''
    from gluon.html import markmin_serializer, TAG
    return TAG(html).flatten(markmin_serializer).lstrip(' ')
Example #6
0
def html_to_markmin(html):
    """
    Replace HTML with Markmin, converting unicode to references first

    >>> html_to_markmin('<p class="foo"><b>Bold</b><i>Italics</i><ol><li>Item 1</li><li><a href="http://kvasir.io">Kvasir</a></li></ol><br>')
    "**Bold**''Italics''\n- Item 1\n- [[Kvasir http://kvasir.io]]\n\n\n\n"
    >>> html_to_markmin(u'<p>asdfsadf</p>')
    'asdfsadf\n\n'
    >>> html_to_markmin(u'<p>\ufffdq\ufffd</p>')
    '\xef\xbf\xbdq\xef\xbf\xbd\n\n'
    >>> html_to_markmin('[[ a link http://url.com]]')
    '[[a link http://url.com]]'
    """
    if html is None:
        return ''
    from gluon.html import markmin_serializer, TAG
    html = html.encode('ascii', 'xmlcharrefreplace')    # cleanup unicode
    html = TAG(html).flatten(markmin_serializer)        # turn to markmin
    html = html.replace('[[ ', '[[')                      # fix bad url
    html = html.replace(' ]]', ']]')                      # fix bad url
    return html
Example #7
0
def pdflatex_from_html(html):
    if os.system('which pdflatex > /dev/null') == 0:
        markmin = TAG(html).element('body').flatten(markmin_serializer)
        out, warnings, errors = markmin2pdf(markmin)
        if errors:
            current.response.headers['Content-Type'] = 'text/html'
            raise HTTP(405, HTML(BODY(H1('errors'),
                                      UL(*errors),
                                      H1('warnings'),
                                      UL(*warnings))).xml())
        else:
            return XML(out)
Example #8
0
def xml_rec(value, key, quote=True):
    if hasattr(value, "custom_xml") and callable(value.custom_xml):
        return value.custom_xml()
    elif isinstance(value, (dict, Storage)):
        return TAG[key](*[TAG[k](xml_rec(v, "", quote)) for k, v in value.items()])
    elif isinstance(value, list):
        return TAG[key](*[TAG.item(xml_rec(item, "", quote)) for item in value])
    elif hasattr(value, "as_list") and callable(value.as_list):
        return str(xml_rec(value.as_list(), "", quote))
    elif hasattr(value, "as_dict") and callable(value.as_dict):
        return str(xml_rec(value.as_dict(), "", quote))
    else:
        return xmlescape(value, quote)
Example #9
0
def xml_rec(value, key, quote=True):
    if hasattr(value, 'custom_xml') and callable(value.custom_xml):
        return value.custom_xml()
    elif isinstance(value, (dict, Storage)):
        return TAG[key](*[TAG[k](xml_rec(v, '', quote))
                          for k, v in value.items()])
    elif isinstance(value, list):
        return TAG[key](*[TAG.item(xml_rec(item, '', quote)) for item in value])
    elif hasattr(value, 'as_list') and callable(value.as_list):
        return str(xml_rec(value.as_list(), '', quote))
    elif hasattr(value, 'as_dict') and callable(value.as_dict):
        return str(xml_rec(value.as_dict(), '', quote))
    else:
        return xmlescape(value, quote)
Example #10
0
 def FONT(*args, **kwargs):
     return TAG.font(*args, **kwargs)
Example #11
0
 def test_TAG_pickler_unpickler(self):
     # weird test
     self.assertEqual(
         TAG_unpickler(TAG_pickler(
             TAG.div('data to be pickle'))[1][0]).xml(),
         b'<div>data to be pickle</div>')
Example #12
0
def latex_from_html(html):
    markmin = TAG(html).element('body').flatten(markmin_serializer)
    return XML(markmin2latex(markmin))
Example #13
0
 def test_TAG_pickler_unpickler(self):
     # weird test
     self.assertEqual(TAG_unpickler(TAG_pickler(TAG.div('data to be pickle'))[1][0]).xml(),
                      b'<div>data to be pickle</div>')
Example #14
0
def ccache():
    form = FORM(
        P(TAG.BUTTON("Clear CACHE?", _type="submit", _name="yes",
                     _value="yes")),
        P(TAG.BUTTON("Clear RAM", _type="submit", _name="ram", _value="ram")),
        P(TAG.BUTTON("Clear DISK", _type="submit", _name="disk",
                     _value="disk")),
    )

    if form.accepts(request.vars, session):
        clear_ram = False
        clear_disk = False
        session.flash = ""
        if request.vars.yes:
            clear_ram = clear_disk = True
        if request.vars.ram:
            clear_ram = True
        if request.vars.disk:
            clear_disk = True

        if clear_ram:
            cache.ram.clear()
            session.flash += "Ram Cleared "
        if clear_disk:
            cache.disk.clear()
            session.flash += "Disk Cleared"

        redirect(URL(r=request))

    try:
        from guppy import hpy
        hp = hpy()
    except ImportError:
        hp = False

    import shelve, os, copy, time, math
    from gluon import portalocker

    ram = {
        'bytes': 0,
        'objects': 0,
        'hits': 0,
        'misses': 0,
        'ratio': 0,
        'oldest': time.time()
    }
    disk = copy.copy(ram)
    total = copy.copy(ram)

    for key, value in cache.ram.storage.items():
        if isinstance(value, dict):
            ram['hits'] = value['hit_total'] - value['misses']
            ram['misses'] = value['misses']
            try:
                ram['ratio'] = ram['hits'] * 100 / value['hit_total']
            except (KeyError, ZeroDivisionError):
                ram['ratio'] = 0
        else:
            if hp:
                ram['bytes'] += hp.iso(value[1]).size
                ram['objects'] += hp.iso(value[1]).count

                if value[0] < ram['oldest']:
                    ram['oldest'] = value[0]

    locker = open(os.path.join(request.folder, 'cache/cache.lock'), 'a')
    portalocker.lock(locker, portalocker.LOCK_EX)
    disk_storage = shelve.open(
        os.path.join(request.folder, 'cache/cache.shelve'))
    try:
        for key, value in disk_storage.items():
            if isinstance(value, dict):
                disk['hits'] = value['hit_total'] - value['misses']
                disk['misses'] = value['misses']
                try:
                    disk['ratio'] = disk['hits'] * 100 / value['hit_total']
                except (KeyError, ZeroDivisionError):
                    disk['ratio'] = 0
            else:
                if hp:
                    disk['bytes'] += hp.iso(value[1]).size
                    disk['objects'] += hp.iso(value[1]).count
                    if value[0] < disk['oldest']:
                        disk['oldest'] = value[0]
    finally:
        portalocker.unlock(locker)
        locker.close()
        disk_storage.close()

    total['bytes'] = ram['bytes'] + disk['bytes']
    total['objects'] = ram['objects'] + disk['objects']
    total['hits'] = ram['hits'] + disk['hits']
    total['misses'] = ram['misses'] + disk['misses']
    try:
        total['ratio'] = total['hits'] * 100 / (total['hits'] +
                                                total['misses'])
    except (KeyError, ZeroDivisionError):
        total['ratio'] = 0

    if disk['oldest'] < ram['oldest']:
        total['oldest'] = disk['oldest']
    else:
        total['oldest'] = ram['oldest']

    def GetInHMS(seconds):
        hours = math.floor(seconds / 3600)
        seconds -= hours * 3600
        minutes = math.floor(seconds / 60)
        seconds -= minutes * 60
        seconds = math.floor(seconds)

        return (hours, minutes, seconds)

    ram['oldest'] = GetInHMS(time.time() - ram['oldest'])
    disk['oldest'] = GetInHMS(time.time() - disk['oldest'])
    total['oldest'] = GetInHMS(time.time() - total['oldest'])

    return dict(form=form, total=total, ram=ram, disk=disk)
Example #15
0
            Field("test1",
                  "string",
                  requires=IS_NOT_EMPTY(),
                  comment="some data"),
            Field("test2",
                  "string",
                  requires=IS_NOT_EMPTY(),
                  comment="some data"),
            Field("test3",
                  "string",
                  requires=IS_NOT_EMPTY(),
                  comment="some data"),
            formname=None,
        )
    elif '--object' in sys.argv:
        form = OBJECT(TAG.PARAM(_name='label', _value='"test"'),
                      TAG.PARAM(_name='name', _value='"btnTest"'),
                      _class="Button",
                      _width="100%",
                      _height="80%")
    else:
        raise RuntimeError(
            "please use\npython forms_example.py --login, --form or --sqlform")

    form_xml = BODY(form,
                    _text="#000000",
                    _bgcolor="#bebec5",
                    _link="#0000FF",
                    _vlink="#FF0000",
                    _alink="#000088").xml()
    print form_xml