import mimetypes


def encode_multipart_formdata(fields, files=None):
    """ Encodes data for multipart form POST

    fields: list of (name,value) tuples or dict
    files: optional list of (name, filename, data) tuples 
    
    Taken from: http://code.activestate.com/recipes/146306/ """

    def generate_boundary():
        return '----------DjshEfhAcVyueShrAltuN'

    boundary = generate_boundary()
    L = [ ]
    if type(fields) == dict:
        fields = fields.items()
    for (key, value) in fields:
        L.append('--{0}'.format(boundary))
        L.append('Content-Disposition: form-data; name="{0}"'.format(key))
        L.append('')
        L.append(value)
    if files:
        for (key, filename, value) in files:
            L.append('--%s' % boundary)
            header = 'Content-Disposition: form-data; name="{0}"; filename' \
                    '="{1}"'.format(key, filename)
            L.append(header)
            t = mimetypes.guess_type(filename)[0]
            L.append('Content-Type: {0}'.format(
                (t or 'application/octet-stream')))
            L.append('')
            L.append(value)
    L.append('--{0}--'.format(boundary))
    L.append('')
    body = '\r\n'.join(L)
    content_type = 'multipart/form-data; boundary={0}'.format(boundary)
    return content_type, body