Mike Orr avatar Mike Orr committed e1f6a36

Delete code that has been released in FormBuild2 and ExtraHelpers packages.

Comments (0)

Files changed (6)

unfinished/experimental.py

-"""Experimental HTML helpers (UNSTABLE!)
-
-HELPERS IN THIS MODULE ARE RELEASED FOR EXPERIMENTATION AND FEEDBACK ONLY.
-THEY MAY CHANGE OR DISAPPEAR IN A FUTURE VERSION OF WebHelpers.  FUNCTIONS
-APPROVED FOR LONG-TERM SUPPORT WILL BE MOVED TO OTHER MODULES.  
-
-If you want to use a function defined here in an application, please copy it to
-the application rather than importing it.
-"""
-
-from webhelpers.html.tags import form as start_form, end_form
-from webhelpers.html import HTML, literal
-#from webhelpers.rails import options_for_select
-
-NL = literal("\n")
-BR = HTML.br() + NL
-
-def form_start(*k, **p):
-    """\
-    Start a form the way you would with ``start_form()`` but include the HTML
-    necessary for the use of the ``fields()`` helper. 
-    
-    >>> form_start('/action', method='post')
-    literal(u'<form action="/action" method="post"><table>')
-    >>> form_start('/action', method='post', table_class='form')
-    literal(u'<form action="/action" method="post"><table class="form">')
-    """
-    if p.has_key('table_class'):
-         table_class = p.get('table_class', 'form')
-         del p['table_class']
-         return start_form(*k,**p) + HTML.table(
-             _closed=False, 
-             class_=p.get('table_class', 'form'),
-         )
-    else:
-         return start_form(*k,**p) + HTML.table(_closed=False)
-
-def form_end(*k, **p):
-    """\
-    End a form started with ``form_start()``
-    >>> form_end()
-    literal(u'</form></table>')
-    """
-    return HTML.tag("/table", _closed=False) + end_form(*k, **p)
-
-def field(
-    label='', 
-    field='', 
-    required=False, 
-    label_desc='', 
-    field_desc='',
-    sub_label='', 
-    help='',
-    error=''
-):
-    """\
-    Format a field with a label. 
-
-    ``label``
-        The label for the field
-
-    ``field``
-        The HTML representing the field.  If not using
-        ``webhelpers.html.tags``, wrap the HTML in a ``literal()``.
-
-    ``required``
-         Can be ``True`` or ``False`` depending on whether the label should be 
-         formatted as required or not. By default required fields have an
-         asterix.
-
-    ``label_desc``
-        Any text to appear underneath the label, level with ``field_desc`` .
-
-    ``field_desc``
-        Any text to appear underneath the field
-
-    ``sub_label``
-        Any text to appear immediately beneath the label but above the 
-        label_desc. This is useful if the field itself is very large and using
-        label_desc would result in the description of the label being a long 
-        way from the label itself.
-
-    ``help``
-        Any HTML or JavaScript to appear imediately to the right of the field 
-        which could be used to implement a help system on the form
-
-    ``error``
-        Any text to appear immediately before the HTML field, usually used for
-        an error message.
-
-    It should be noted that when used with FormEncode's ``htmlfill`` module, 
-    errors appear immediately before the HTML field in the position of the
-    ``error`` argument. No ``<form:error>`` tags are added automatically by
-    this helper because errors are placed there anyway and adding the tags
-    would lead to this helper generating invalid HTML.
-    """
-    field = error + field
-    if label:
-        label = label + literal(":")
-    output = []
-    if required:
-        required = HTML.span("*", class_="required")
-    else:
-        required = ""
-    desc = ""
-    if sub_label:
-        desc = HTML.br() + HTML.span(sub_label, class_="small")
-    if help:
-        output.append(
-            HTML.tr(class_="field", c=[
-                HTML.td(class_="label", valign="top", c=[
-                    required, HTML.label(label), desc),
-                    class_="label", valign="top")
-                    ]
-                ]
-            )
-        output.append(literal('<tr class="field"><td valign="top" class="label">')+required+HTML.label(c=label)+desc+literal('</td><td>')+field+literal('</td><td>')+help+literal('</td></tr>'))
-    else:
-        output.append(literal('<tr class="field"><td valign="top" class="label">')+required+HTML.label(c=label)+desc+literal('</td><td colspan="2">')+field+literal('</td></tr>'))
-    if label_desc or field_desc:
-        output.append(literal('<tr class="description"><td valign="top" class="label"><span class="small">')+label_desc+literal('</span></td><td valign="top" colspan="2"><span class="small">')+field_desc+literal('</span></td></tr>'))
-    return ''.join(output)
-
-
-
-def options_with_caption(container, caption='Please select...', pos=0, value='', *k, **p):
-    """\
-    Return a some select options adding in a value of '' with a caption specified by ``text``.
-    """
-    if pos=='end':
-        container.append([caption, value])
-    else:
-        container.insert(pos, [caption, value])
-    return options_for_select(container, *k, **p)
-
-def ids_from_options(options):
-    """\
-    Return the IDs of all the options used to create a select box. Useful when using
-    a ``OneOf`` formencode validator.
-    """
-    return [str(x[1]) for x in options]
-
-def value_from_option_id(options, id):
-    """\
-    Attempts to return a value for the option specified, returns ``""``
-    if the option specified is ``None`` so that it works with the 
-    ``options_with_please_select()`` helper above. 
-    """
-    if not id:
-        return ''
-    if isinstance(options, (list, tuple)):
-        if len(options) and isinstance(options[0], (list, tuple)):
-            for v, k in options:
-                if unicode(k) == unicode(id):
-                    return v
-        else:
-            # Assume it is a list where the ids are the values:
-            if unicode(id) in [unicode(x) for x in options]:
-                return id
-    raise Exception("Option %s not found or invalid option format"%id)
-    
-#def radio_group(name, options, value=None, align='horiz', cols=4):
-#    """Radio Group Field."""
-#    output=''
-#    if len(options)>0:
-#        if align <> 'table':
-#            for option in options:
-#                checked=''
-#                if not isinstance(option, list) and not isinstance(option, tuple):
-#                    k = option
-#                    v = option
-#                else:
-#                    k, v = option
-#                if unicode(v) == unicode(value):
-#                    checked=" checked"
-#                break_ = ''
-#                if align == 'vert':
-#                    break_='<br />'
-#                output+='<input type="radio" name="%s" value="%s"%s /> %s%s\n'%(name, v, checked, k, break_)
-#        else:
-#            output += '<table border="0" width="100%" cellpadding="0" cellspacing="0">\n    <tr>\n'
-#            counter = -1
-#            for option in options:
-#                counter += 1
-#                if ((counter % cols) == 0) and (counter <> 0):
-#                    output += '    </tr>\n    <tr>\n'
-#                output += '      <td>'
-#                checked=''
-#                align=''
-#                if not isinstance(option, list) and not isinstance(option, tuple):
-#                    k = option
-#                    v = option
-#                else:
-#                    k=option[0]
-#                    v=option[1]
-#                if unicode(v)==unicode(value):
-#                    checked=" checked"
-#                output += '<input type="radio" name="%s" value="%s"%s /> %s%s'%(name, v, checked, k,align)
-#                output += '</td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n'
-#            counter += 1
-#            while (counter % cols):
-#                counter += 1
-#                output += '      <td></td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n'
-#            output += '    </tr>\n</table>'
-#    return output
-
-def _format_values(values):
-    if not isinstance(values, list) and not isinstance(values, tuple):
-        return [unicode(values)]
-    else:
-        values_ = []
-        for value in values:
-            values_.append(unicode(value))
-        return values_
-
-def radio_group(name, options, values=None, align='horiz', cols=4):
-    return group(name, options, values, align, cols, 'radio')
-
-def checkbox_group(name, options, values=None, align='horiz', cols=4):
-    return group(name, options, values, align, cols, 'checkbox')
-
-def group(name, options, values=None, align='horiz', cols=4, group_type='checkbox'):
-    """Check Box Group Field."""
-    if not group_type in ['checkbox','radio']:
-        raise Exception('Invalid group type %s'%group_type)
-    values = _format_values(values)
-    output = u''
-    item_counter = 0
-    if len(options) > 0:
-        if align <> 'table':
-            for option in options:
-                if not isinstance(option, list) and not isinstance(option, tuple):
-                    k = option
-                    v = option
-                else:
-                    k=option[0]
-                    v=option[1]
-                checked=literal(u'')
-                if unicode(v) in values:
-                    checked=literal(" checked")
-                break_ = u''
-                if align == 'vert':
-                    break_=literal(u'<br />')
-                output+=literal('<input type="')+literal(group_type)+literal('" name="')+name+literal('" value="')+literal(unicode(v))+literal('" ')+checked+literal(' />')+unicode(k)+break_+literal('\n')
-                item_counter += 1
-        else:
-            output += literal(u'<table border="0" width="100%" cellpadding="0" cellspacing="0">\n    <tr>\n')
-            counter = -1
-            for option in options:
-                counter += 1
-                if ((counter % cols) == 0) and (counter <> 0):
-                    output += literal(u'    </tr>\n    <tr>\n')
-                output += literal('      <td>')
-                checked=literal(u'')
-                align=literal(u'')
-                if not isinstance(option, list) and not isinstance(option, tuple):
-                    k = option
-                    v = option
-                else:
-                    k=option[0]
-                    v=option[1]
-                if unicode(v) in values:
-                    checked=literal(" checked")
-                output+=literal('<input type="checkbox" name="')+name+literal('" value="')+literal(unicode(v))+literal('" ')+checked+literal(' />')+unicode(k)
-                #output += u'<input type="checkbox" name="%s" value="%s"%s />%s%s'%(name, v, checked, k, align)
-                item_counter += 1
-                output += literal(u'</td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n')
-            counter += 1
-            while (counter % cols):
-                counter += 1
-                output += literal(u'      <td></td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n')
-            output += literal(u'    </tr>\n</table>\n')
-    if not type(output) in [unicode, literal]:
-        raise Exception(type(output))
-    return output[:-1]
-
-if __name__ == '__main__':
-    import doctest
-    doctest.testmod()
-

unfinished/fields.py

-"""\
-Functions to help in the formatting of forms
-"""
-
-from webhelpers.html.tags import form as start_form, end_form
-from webhelpers.html import HTML, literal
-from webhelpers.rails import options_for_select
-
-def form_start(*k, **p):
-    """\
-    Start a form the way you would with ``start_form()`` but include the HTML
-    necessary for the use of the ``fields()`` helper. 
-    
-    >>> form_start('/action', method='post')
-    literal(u'<form action="/action" method="post"><table>')
-    >>> form_start('/action', method='post', table_class='form')
-    literal(u'<form action="/action" method="post"><table class="form">')
-    """
-    if p.has_key('table_class'):
-         table_class = p.get('table_class', 'form')
-         del p['table_class']
-         return start_form(*k,**p)+ HTML.table(
-             _closed=False, 
-             class_=p.get('table_class', 'form'),
-         )
-    else:
-         return start_form(*k,**p)+literal('<table>')
-
-def form_end(*k, **p):
-    """\
-    End a form started with ``form_start()``
-    >>> form_end()
-    literal(u'</form></table>')
-    """
-    return literal("</table>")+end_form(*k, **p)
-
-def field(
-    label='', 
-    field='', 
-    required=False, 
-    label_desc='', 
-    field_desc='',
-    sub_label='', 
-    help='',
-    error=''
-):
-    """\
-    Format a field with a label. 
-
-    ``label``
-        The label for the field
-
-    ``field``
-        The HTML representing the field, wrapped in ``literal()``
-
-    ``required``
-         Can be ``True`` or ``False`` depending on whether the label should be 
-         formatted as required or not. By default required fields have an
-         asterix.
-
-    ``label_desc``
-        Any text to appear underneath the label, level with ``field_desc`` 
-
-    ``field_desc``
-        Any text to appear underneath the field
-
-    ``sub_label``
-        Any text to appear immediately beneath the label but above the 
-        label_desc. This is useful if the field itself is very large and using
-        label_desc would result in the description of the label being a long 
-        way from the label itself.
-
-    ``help``
-        Any HTML or JavaScript to appear imediately to the right of the field 
-        which could be used to implement a help system on the form
-
-    ``error``
-        Any text to appear immediately before the HTML field, usually used for
-        an error message.
-
-    It should be noted that when used with FormEncode's ``htmlfill`` module, 
-    errors appear immediately before the HTML field in the position of the
-    ``error`` argument. No ``<form:error>`` tags are added automatically by
-    this helper because errors are placed there anyway and adding the tags
-    would lead to this helper generating invalid HTML.
-    """
-    field = error+field
-    if label:
-        label = label + literal(':')
-    output = []
-    if required:
-        required = HTML.span(class_="required", c='*')
-    else:
-        required = ''
-    desc = ''
-    if sub_label:
-        desc = '<br /><span class="small">%s</span>'%sub_label
-    if help:
-        output.append(literal('<tr class="field"><td valign="top" class="label">')+required+HTML.label(c=label)+desc+literal('</td><td>')+field+literal('</td><td>')+help+literal('</td></tr>'))
-    else:
-        output.append(literal('<tr class="field"><td valign="top" class="label">')+required+HTML.label(c=label)+desc+literal('</td><td colspan="2">')+field+literal('</td></tr>'))
-    if label_desc or field_desc:
-        output.append(literal('<tr class="description"><td valign="top" class="label"><span class="small">')+label_desc+literal('</span></td><td valign="top" colspan="2"><span class="small">')+field_desc+literal('</span></td></tr>'))
-    return ''.join(output)
-
-
-
-def options_with_caption(container, caption='Please select...', pos=0, value='', *k, **p):
-    """\
-    Return a some select options adding in a value of '' with a caption specified by ``text``.
-    """
-    if pos=='end':
-        container.append([caption, value])
-    else:
-        container.insert(pos, [caption, value])
-    return options_for_select(container, *k, **p)
-
-def ids_from_options(options):
-    """\
-    Return the IDs of all the options used to create a select box. Useful when using
-    a ``OneOf`` formencode validator.
-    """
-    return [str(x[1]) for x in options]
-
-def value_from_option_id(options, id):
-    """\
-    Attempts to return a value for the option specified, returns ``""``
-    if the option specified is ``None`` so that it works with the 
-    ``options_with_please_select()`` helper above. 
-    """
-    if not id:
-        return ''
-    if isinstance(options, (list, tuple)):
-        if len(options) and isinstance(options[0], (list, tuple)):
-            for v, k in options:
-                if unicode(k) == unicode(id):
-                    return v
-        else:
-            # Assume it is a list where the ids are the values:
-            if unicode(id) in [unicode(x) for x in options]:
-                return id
-    raise Exception("Option %s not found or invalid option format"%id)
-    
-#def radio_group(name, options, value=None, align='horiz', cols=4):
-#    """Radio Group Field."""
-#    output=''
-#    if len(options)>0:
-#        if align <> 'table':
-#            for option in options:
-#                checked=''
-#                if not isinstance(option, list) and not isinstance(option, tuple):
-#                    k = option
-#                    v = option
-#                else:
-#                    k, v = option
-#                if unicode(v) == unicode(value):
-#                    checked=" checked"
-#                break_ = ''
-#                if align == 'vert':
-#                    break_='<br />'
-#                output+='<input type="radio" name="%s" value="%s"%s /> %s%s\n'%(name, v, checked, k, break_)
-#        else:
-#            output += '<table border="0" width="100%" cellpadding="0" cellspacing="0">\n    <tr>\n'
-#            counter = -1
-#            for option in options:
-#                counter += 1
-#                if ((counter % cols) == 0) and (counter <> 0):
-#                    output += '    </tr>\n    <tr>\n'
-#                output += '      <td>'
-#                checked=''
-#                align=''
-#                if not isinstance(option, list) and not isinstance(option, tuple):
-#                    k = option
-#                    v = option
-#                else:
-#                    k=option[0]
-#                    v=option[1]
-#                if unicode(v)==unicode(value):
-#                    checked=" checked"
-#                output += '<input type="radio" name="%s" value="%s"%s /> %s%s'%(name, v, checked, k,align)
-#                output += '</td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n'
-#            counter += 1
-#            while (counter % cols):
-#                counter += 1
-#                output += '      <td></td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n'
-#            output += '    </tr>\n</table>'
-#    return output
-
-def _format_values(values):
-    if not isinstance(values, list) and not isinstance(values, tuple):
-        return [unicode(values)]
-    else:
-        values_ = []
-        for value in values:
-            values_.append(unicode(value))
-        return values_
-
-def radio_group(name, options, values=None, align='horiz', cols=4):
-    return group(name, options, values, align, cols, 'radio')
-
-def checkbox_group(name, options, values=None, align='horiz', cols=4):
-    return group(name, options, values, align, cols, 'checkbox')
-
-def group(name, options, values=None, align='horiz', cols=4, group_type='checkbox'):
-    """Check Box Group Field."""
-    if not group_type in ['checkbox','radio']:
-        raise Exception('Invalid group type %s'%group_type)
-    values = _format_values(values)
-    output = u''
-    item_counter = 0
-    if len(options) > 0:
-        if align <> 'table':
-            for option in options:
-                if not isinstance(option, list) and not isinstance(option, tuple):
-                    k = option
-                    v = option
-                else:
-                    k=option[0]
-                    v=option[1]
-                checked=literal(u'')
-                if unicode(v) in values:
-                    checked=literal(" checked")
-                break_ = u''
-                if align == 'vert':
-                    break_=literal(u'<br />')
-                output+=literal('<input type="')+literal(group_type)+literal('" name="')+name+literal('" value="')+literal(unicode(v))+literal('" ')+checked+literal(' />')+unicode(k)+break_+literal('\n')
-                item_counter += 1
-        else:
-            output += literal(u'<table border="0" width="100%" cellpadding="0" cellspacing="0">\n    <tr>\n')
-            counter = -1
-            for option in options:
-                counter += 1
-                if ((counter % cols) == 0) and (counter <> 0):
-                    output += literal(u'    </tr>\n    <tr>\n')
-                output += literal('      <td>')
-                checked=literal(u'')
-                align=literal(u'')
-                if not isinstance(option, list) and not isinstance(option, tuple):
-                    k = option
-                    v = option
-                else:
-                    k=option[0]
-                    v=option[1]
-                if unicode(v) in values:
-                    checked=literal(" checked")
-                output+=literal('<input type="checkbox" name="')+name+literal('" value="')+literal(unicode(v))+literal('" ')+checked+literal(' />')+unicode(k)
-                #output += u'<input type="checkbox" name="%s" value="%s"%s />%s%s'%(name, v, checked, k, align)
-                item_counter += 1
-                output += literal(u'</td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n')
-            counter += 1
-            while (counter % cols):
-                counter += 1
-                output += literal(u'      <td></td>\n      <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n')
-            output += literal(u'    </tr>\n</table>\n')
-    if not type(output) in [unicode, literal]:
-        raise Exception(type(output))
-    return output[:-1]
-
-if __name__ == '__main__':
-    import doctest
-    doctest.testmod()
-

unfinished/group.py

-def checkbox_group(name, selected_values, options, nrows=None):
-    """Return a group of checkboxes arranged in columns.  See ``group()``.
-    """
-    return group(name, selected_values, options, nrows, "checkbox")
-
-def radio_group(name, selected_values, options, nrows):
-    """Return a group of radio buttons  arranged in columns.  See ``group()``.
-    """
-    return group(name, selected_values, options, nrows=None, "radio")
-
-
-def group(name, selected_values, options, nrows=None, input_type="checkbox"):
-    """Return a group of checkboxes or radio buttons arranged in columns.
-
-    The current implementation puts the widgets in an 
-    ``<ul class="field-group">``, with a ``<div class="field-group-column">``
-    around each column, and a ``<fieldset class="field-group>"`` around the
-    whole thing.  You'll have to set an appropriate style for this
-    class in order to get the column effect; 
-    e.g., "div.field-group-column {float:left, margin-right: 2em}".
-
-    Arguments:
-
-      ``name`` -- name of the widget group (<input name=>).
-
-      ``selected_values`` -- list or tuple of previously-selected values.
-          Pass ``None`` to not select any.
-
-      ``options`` -- a list of ``Option`` objects or ``(value, label)``
-          pairs.  See ``select()`` for the range of legal values.
-
-      ``nrows`` -- number of rows (i.e., max number of widgets per column).
-
-      ``input_type`` -- "checkbox" or "radio".
-    """
-    if input_type not in ["checkbox", "radio"]:
-        raise ValueError("input type must be 'checkbox' or 'radio'")
-    if not isinstance(options, Options):
-        options = Options(options)
-    html_options = [
-        HTML.label(
-            HTML.input(type=input_type, name=name, value=x.value),
-            x.label)
-        for x in options]
-    # Distribute the elements horizontally or vertically into a 2D list
-    # in row-major order.
-    array = containers.distribute(options_html, ncol, direction)
-    # Turn the list sideways to make it column-major.
-    columns = containers.transpose(array)
-    # Format each column into a <div>.
-    for i, col in enumerate(columns):
-        col = BR.join(columns[i])
-        columns[i] = HTML.div(c=col, style="float:left; margin-right: 2em")
-    return HTML.div(NL, NL.join(columns), NL)
-            
-

unfinished/helpers.py

-"""\
-A series of useful helper functions which aren't found in other libraries.
-"""
-
-
-def divide(a,b):
-    """\
-    Divides the fisrt argument by the second, returning an integer if possible, a float otherwise.
-
-    For example::
-
-        >>> divide(3,2)
-        1.5
-        >>> divide(3,1)
-        3
-    """
-    if a%b:
-        return a/float(b)
-    else:
-        return a/b
-
-def size_to_human(
-    size, 
-    format='binary', 
-    units=['B','KB','MB','GB','TB','PB','EB'], 
-    digits = 4
-):
-    """\
-    Converts an size in bytes to a human-readable format.  The following
-    website outlines some of the issues involved with sizes:
-    http://www.t1shopper.com/tools/calculate/
-
-    ``size``
-
-        The size as a number of bytes
-
-    ``format``
-
-        Whether you want to count 1000 bytes in a kilobyte like hard drive
-        manufactures do ("decimal") or 1024 bytes in a kilobyte like everyone
-        else does ("binary"). The default is "binary".
-
-    ``units``
-
-        The units you wish to use a list starting with the units for bytes and
-        going up in factors of 1000 as far as you like. The defaults are
-        sensible but this option allows you to use the new IEC units if you
-        wish.
-
-    ``digits``
-
-        The number of digits to display in the result if there is a decimal.
-        For example if the result was 522.67 KB this would become 522.7 KB if
-        ``digits`` was 4. If ``digits`` was 3 it would be 523 KB.
-
-        Set to ``0`` to display the whole result without formatting.
-
-    Here are some examples:
-
-        >>> size_to_human(534)
-        '534 B'
-        >>> size_to_human(534813)
-        '522.3 KB'
-        >>> size_to_human(534813000)
-        '510 MB'
-        >>> size_to_human(534813, format='decimal')
-        '534.8 KB'
-        >>> size_to_human(534813, digits=3)
-        '522 KB'
-        >>> size_to_human(1024**5, digits=0)
-        '1 PB'
-        >>> size_to_human(1024**6, digits=0)
-        '1 EB'
-        >>> size_to_human(1024**7, digits=0)
-        '1024 EB'
-        >>> size_to_human(534813, units=['B','KiB','MiB','GiB','TiB','PiB','EiB'])
-        '522.3 KB'
-
-    >>> size_to_human(534813)
-    '522.3 KB'
-    >>> size_to_human(534813, format='decimal')
-    '534.8 KB'
-    """
-    if format == 'binary':  
-        format = 1024
-    elif format == 'decimal':
-        format = 1000
-    else:
-        raise Exception('Can only convert sizes in binary or decimal format, not %r'%format)
-    size=int(size)
-    units=['B','KB','MB','GB','TB','PB','EB']
-    counter = 0
-    while (size>=format and counter<len(units)-1):
-        size = divide(size, format)
-        counter += 1
-    if digits:
-        size_ = str(size)
-        if ('.' in size_) and (len(size_) > digits+1):
-            number_of_digits_after_decimal = len(size_.split('.')[-1])
-            number_of_digits_too_many = len(size_)-digits-1
-            round_to = number_of_digits_after_decimal - number_of_digits_too_many
-            size = round(size, round_to)
-
-    if size == long(size):
-        size = long(size)
-    return "%s %s"%(size, units[counter])
-
-if __name__ == '__main__':
-    import doctest
-    doctest.testmod()
-

unfinished/mail.py

-"""\
-Set of helpers to make sending email easier.
-
-If you already have a ``Message`` based on the Python standard libraries
-``email.message.Message`` you can send it like this::
-
-    send(
-        message, 
-        smtp='smtp.example.com', 
-        username='myusername', 
-        password='mypassword'
-    )
-
-Or like this::
-
-    send(message, sendmail='/usr/bin/sendmail')
-
-If you have a message but haven't added key things like who it is to or from
-you can add them like this::
-
-    prepare(
-        message,
-        from_name = 'James Gardner',
-        from_email = 'james@example.com',
-        to=['Jeremey <jeremey@example.com>', 'kate@example.com'], 
-        cc=[], 
-        bcc=[], 
-        subject='Test Email',
-    )
-
-If you haven't created a message at all and want a plain text email you can do
-this::
-
-    message_text = '''\
-    Hi Jim,
-
-    This is a simple plain text email.
-
-    Regards, 
-
-    James
-    '''
-
-    message = plain(message_text)
-
-If you want a multi-part message for attaching files etc you generate it
-slightly differently:
-
-    message_text = '''\
-    Hi Jim,
-
-    Here is my holiday photo.
-
-    Regards, 
-
-    James
-    '''
-
-    message = multi(
-        preamble = 'Only non-MIME aware email clients see this text',
-        parts = [
-            part(message_text, content_type='text/plain'),
-            part(filename='photo.jpg'),
-        ],
-    )
-    
-Putting this all togehter you can do it all at once like this::
-
-    send(
-        prepare(
-            plain("Hi Jim\nHere's the photo.\n\nJames"),
-            from_name = 'James Gardner',
-            from_email = 'james@example.com',
-            to=['Jeremey <jeremey@example.com>'], 
-            subject='Holiday Photos',
-        ),
-        sendmail='/usr/bin/sendmail',
-    )
-"""
-
-from email import Utils
-import mimetypes
-import os
-import smtplib
-
-from email.MIMEText import MIMEText
-from email.MIMEBase import MIMEBase
-from email.MIMEMultipart import MIMEMultipart
-from email import Encoders
-
-class MailError(Exception):
-    "Generic problem buidling a message or sending a mail"
-
-def _prepare(
-    message,
-    from_name,
-    from_email,
-    to=[], 
-    cc=[], 
-    bcc=[], 
-    subject='(no subject)',
-):
-    if not to and not cc and not bcc:
-        raise MailError("No recipients specified")
-    message['From'] = Utils.formataddr((from_name, from_email))
-    message['Subject'] = subject
-    if isinstance(to, (unicode, str)):
-        to=[to]
-    if to:
-        message['To'] = ', '.join(to)
-    if isinstance(cc, (unicode, str)):
-        cc=[cc]
-    if cc:
-        message['Cc'] = ', '.join(cc)
-    if isinstance(bcc, (unicode, str)):
-        bcc=[bcc]
-    if bcc:
-        message['Bcc'] = ', '.join(bcc)
-    return message
-
-def plain(
-    text,
-    type='plain',
-    charset=None,
-    **prepare_options
-):
-    """
-    
-    ``**prepare_options`` 
-        Any extra keyword argument are sent to ``_prepare()`` to add standard 
-        information to the message.
-    """
-    if charset is None:
-        message = MIMEText(text, type)
-    else:
-        message = MIMEText(text, type, charset)
-    if prepare_options:
-        message = _prepare(message, **prepare_options)
-    return message
-
-def part(
-    data=None,
-    filename=None,
-    content_type=None,
-    attach=True,
-):
-    """\
-    Create a MIME part to include in the message.
-
-    ``data`` 
-        The data to include. If not specified the contents of the file
-        specified by ``filename`` are used.
-
-    ``filename``
-        The filename of the file to use for the data if ``data`` is not
-        specified. If ``attach`` is ``True`` this filename is used as the
-        filename of the attachment in the resulting email.
-
-    ``content_type`` 
-        The content type of the part, for example ``"text/plain"``. If not
-        specified the content type will be guessed from the filename.
-
-    ``attach``
-        If ``True`` the part will be set up as an attachment. This is probably
-        what you want for photos and the like but not what you want for plain
-        text attachments which you want treated as the body of the email.
-    """
-    if not filename and not data:
-        raise MailError("You must specify a filename or some data")
-    if filename and not content_type:
-        main_type, sub_type = mimetypes.guess_type(filename)
-    elif not content_type:
-        raise MailError("Please specify a content type")
-    else:
-        main_type, sub_type = content_type.split('/')
-    if filename and not data:
-        fp = open(filename, 'rb')
-        data = fp.read()
-        fp.close()
-    part = MIMEBase(main_type, sub_type)
-    part.set_payload(data)
-    Encoders.encode_base64(part)
-    if attach:
-        if filename:
-            # Set the filename parameter
-            part.add_header(
-                'Content-Disposition',
-                'attachment',
-                filename=filename.replace('\\','/').strip('/').split('/')[-1],
-            )
-        else:
-            part.add_header('Content-Disposition', 'attachment')
-    return part
-
-def multi(
-    preamble = None,
-    parts = [],
-    **prepare_options
-):
-    """\
-    Assemble a multi-part MIME message.
-
-    ``preamble``
-        Text to display before the message parts which will be seen only by
-        email clients which don't support MIME.
-
-    ``parts``
-        A list of the MIME parts to add to this message. You can use ``part()``
-        to create each part.
-
-    ``**prepare_options`` 
-        Any extra keyword argument are sent to ``_prepare()`` to add standard 
-        information to the message.
-    
-    """
-    message = MIMEMultipart()
-    if preamble is not None:
-        message.preamble = preamble
-    for part in parts:
-        message.attach(part)
-    if prepare_options:
-        message = _prepare(message, **prepare_options)
-    return message
-
-def send(
-    message,
-    smtp=None, 
-    username=None,
-    password=None,
-    port=None,
-    verbose=False,
-    sendmail=None,
-):
-    """\
-    Send an email message via SMTP or Sendmail.
-
-    Whether to send the message via sendmail or SMTP is determined by
-    whether you specify an SMTP server address or a sendmail path. You 
-    should not specify both.
-
-    ``smtp``
-        The SMTP server address you want to use to send the mail. You
-        should not specify both ``sendmail`` and ``smtp``.
-
-    ``username``
-        The username for the SMTP server, if required.
-
-    ``password``
-        The password for the SMTP server, if required.
-
-    ``port``
-        The SMTP server's port, if required.
-
-    ``verbose``
-        Set to ``True`` if you want all manner of information displayed 
-        spewed out for debugging.
-
-    ``sendmail``
-       Path to the sendmail binary (or sendmail compatible binary) which is
-       usually something like ``/usr/bin/sendmail`` or ``/usr/sbin/sendmail``
-       or ``/usr/local/bin/sendmail``. You should not specify both ``sendmail``
-       and ``smtp``.
-    """    
-    if sendmail and smtp:
-        raise MailError("Please specify either sendmail or smtp, not both")
-    if not sendmail and not smtp:
-        raise MailError("You must specify an SMTP server or Sendmail binary path")
-    if sendmail:
-        # No further processing required, sendmail handles the rest
-        if not os.path.exists(sendmail):
-            raise MailError(
-                "The path '%s' doesn't exist. Please check the location of "
-                "sendmail."%(
-                    sendmail
-                )
-            )
-        data = message.as_string()
-        print data
-        cmd = sendmail+" -t"
-        if verbose:
-            cmd+= " -v"
-        fp = os.popen(cmd, 'w')
-        fp.write(data)
-        error = fp.close()
-        if error:
-            raise MailError("Error sending mail: Sendmail Error '%s'."% error)
-    else:
-        # We are using SMTP
-        s = smtplib.SMTP()
-        if verbose:
-            s.set_debuglevel(100)
-        if port:
-           s.connect(smtp, port)
-        else:
-            s.connect(smtp)
-        if username:
-            s.login(username, password)
-        all = []
-        if message['To']:
-            to = message['To'].strip().strip(',').split(',')
-            for address in to:
-                if address:
-                    all.append(address)
-        if message['Cc']:
-            cc = message['Cc'].strip().strip(',')
-            for address in cc.split(','):
-                if address:
-                    all.append(address)
-        if message['Bcc']:
-            bcc = message['Bcc'].strip().strip(',')
-            for address in bcc.split(','):
-                if address:
-                    all.append(address)
-        # Let's remove the Bcc part just to make sure:
-        message['Bcc'] = ''
-        result = s.sendmail(message['From'], all, message.as_string())
-        s.quit()
-        if result:
-            for r in result.keys():
-                error+= "Error sending to"+ str(r)
-                rt = result[r]
-                error+= "Code"+ str(rt[0])+":"+ str(rt[1])
-            raise MailError("Error sending mail: %s"% error)
-

unfinished/test_mail.py

-#!/usr/bin/env python
-
-"""Test program to send mail to recipients.
-
-Use the -s option with nose to have the verbose output logged and for the raw_input text to be displayed.
-
-So, you run this test like this from the root of the webhelpers.mail package::
-    
-    ~/bin/nosetests test/test_mail.py -s 
-"""
-import sys; sys.path.append('../')
-import webhelpers.mail
-
-# Simulate a Pylons helpers setup
-class H:
-    mail = webhelpers.mail
-h=H()
-
-def setup():
-    global address, ccaddress, bccaddress, smtp, username, password
-    address = raw_input('Email address to recieve tests: ')
-    ccaddress = raw_input('Email another address to recieve tests: ')
-    bccaddress = raw_input('Email another address to recieve tests: ')
-    smtp = raw_input('SMTP Server: ')
-    username = raw_input('Username: ')
-    password = raw_input('Password: ')
-
-def test_sendmail_plain():
-    h.mail.send(
-        h.mail.plain(
-            "Hi Jim\n\nHere's the photo from sendmail.\n\nJames",
-            from_name = 'James Gardner',
-            from_email = address,
-            to=[address], 
-            subject='Holiday Photos',
-        ),
-        sendmail='/usr/sbin/sendmail',
-        verbose=True
-    )
-
-def test_sendmail_multi():
-    h.mail.send(
-        h.mail.multi(
-            parts = [
-                h.mail.part("Here is the photo from sendmail again.", content_type="text/plain", attach=False),
-                h.mail.part(filename='test/attachment.jpg'),
-            ],
-            from_name = 'James Gardner',
-            from_email = address,
-            to=['Test Address <'+address+'>'], 
-            cc=['Test Address CC <'+ccaddress+'>'], 
-            bcc=['Test Address BCC <'+bccaddress+'>'], 
-            subject='Holiday Photos',
-        ),
-        smtp=smtp,
-        username=username,
-        password = password,
-        verbose=True,
-    )
-
-def test_smtp_plain():
-    h.mail.send(
-        h.mail.plain(
-            "Hi Jim\n\nHere's the photo from SMTP.\n\nJames",
-            from_name = 'James Gardner',
-            from_email = address,
-            to=[address], 
-            subject='Holiday Photos',
-        ),
-        smtp=smtp,
-        username=username,
-        password = password,
-        verbose=True,
-    )
-    
-def test_smtp_multi():
-    h.mail.send(
-        h.mail.multi(
-            parts = [
-                h.mail.part("Here is the photo from SMTP again.", content_type="text/plain", attach=False),
-                h.mail.part(filename='test/attachment.jpg'),
-            ],
-            from_name = 'James Gardner',
-            from_email = address,
-            to=['Test Address <'+address+'>'], 
-            cc=['Test Address CC <'+ccaddress+'>'], 
-            bcc=['Test Address BCC <'+bccaddress+'>'], 
-            subject='Holiday Photos',
-        ),
-        smtp=smtp,
-        username=username,
-        password = password,
-        verbose=True,
-    )
-
-def test_smtp_html():
-    h.mail.send(
-        h.mail.multi(
-            parts = [
-                h.mail.part("<html>This is an <b>html</b> email</html>", content_type="text/html", attach=False),
-                h.mail.part(filename='test/attachment.jpg'),
-            ],
-            preamble='This is an HTML email but your email client does not support mulit-part emails.',
-            from_name = 'James Gardner',
-            from_email = address,
-            to=[address], 
-            subject='Holiday Photos',
-        ),
-        smtp=smtp,
-        username=username,
-        password = password,
-        verbose=True,
-    )
-
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.