User Tools

Site Tools


python:internet

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python:internet [2014/08/16 09:56] – [post multipart form data] adminpython:internet [2022/10/29 16:15] (current) – external edit 127.0.0.1
Line 372: Line 372:
 PHPSESSID 01eg0u7uf5bm3r01h6pnrv3q33 PHPSESSID 01eg0u7uf5bm3r01h6pnrv3q33
 </code> </code>
-==== post multipart form data ==== +==== Post multipart form data ==== 
-  Post with httplib:  +=== post with encode_multipart_formdata === 
-    * Install:<code bash> +Post with httplib<code python>
-pip install MultipartPostHandler +
-</code> +
-    * example:<code python>+
 import httplib, mimetypes import httplib, mimetypes
  
Line 426: Line 423:
     return mimetypes.guess_type(filename)[0] or 'application/octet-stream'     return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
 </code> </code>
-  * Post using MultipartPostHandler<code python>+=== fix encode_multipart_formdata for posting binary file === 
 +<code python> 
 +def encode_multipart_formdata(fields, files): 
 +    """ 
 +    fields is a sequence of (name, value) elements for regular form fields. 
 +    files is a sequence of (name, filename, value) elements for data to be uploaded as files 
 +    Return (content_type, body) ready for httplib.HTTP instance 
 +    """     
 +     
 +    buf = StringIO() 
 +    boundary = mimetools.choose_boundary()             
 +    for (key, value) in fields: 
 +        buf.write('--%s\r\n' % boundary) 
 +        buf.write('Content-Disposition: form-data; name="%s"' % key) 
 +        buf.write('\r\n\r\n' + value + '\r\n'
 +    for (key, filename, value) in files: 
 +        contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' 
 +        buf.write('--%s\r\n' % boundary) 
 +        buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)) 
 +        buf.write('Content-Type: %s\r\n' % contenttype) 
 +        buf.write('\r\n' + value + '\r\n'
 +    buf.write('--' + boundary + '--\r\n\r\n'
 +    buf = buf.getvalue() 
 +    content_type = 'multipart/form-data; boundary=%s' % boundary 
 +    return content_type, buf 
 +</code> 
 +=== Post using MultipartPostHandler === 
 +  * Install:<code bash> 
 +pip install MultipartPostHandler 
 +</code> 
 +  * example:<code python>
 import MultipartPostHandler, urllib2, cookielib import MultipartPostHandler, urllib2, cookielib
  
python/internet.1408182985.txt.gz · Last modified: 2022/10/29 16:15 (external edit)