~jmillikin/+junk/python-multipart

« back to all changes in this revision

Viewing changes to multipart.py

  • Committer: John Millikin
  • Date: 2008-09-25 00:52:14 UTC
  • Revision ID: jmillikin@gmail.com-20080925005214-1bxlsurkahk7i69e
Implemented generation of a random boundary.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
import mimetypes
 
2
import random
 
3
import string
 
4
from itertools import repeat
2
5
 
3
6
__all__ = ['encode']
4
7
 
17
20
                return ctype
18
21
        return 'application/octet-stream'
19
22
        
 
23
def get_boundary (user_boundary, size = 20):
 
24
        """Generate a random boundary with at least ``size`` characters.
 
25
        
 
26
        If ``user_boundary`` is not ``None``, return it instead.
 
27
        
 
28
        """
 
29
        if user_boundary:
 
30
                return user_boundary
 
31
        rand_digit = lambda: random.choice (string.digits)
 
32
        digits = ''.join (r() for r in repeat (rand_digit, size))
 
33
        return '----------' + digits
 
34
        
20
35
def _encode_field (key, value, boundary):
21
36
        yield '--%s\r\n' % boundary
22
37
        yield 'Content-Disposition: form-data; name="%s"\r\n' % key
49
64
        the encoded parameters.
50
65
        
51
66
        """
 
67
        boundary = get_boundary (boundary)
52
68
        content = []
53
69
        for key, value in params.items ():
54
70
                try: