home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / launchpadbugs / multipartpost_handler.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  4.9 KB  |  133 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. Usage:
  6.   Enables the use of multipart/form-data for posting forms
  7.  
  8. Inspirations:
  9.   Upload files in python:
  10.     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  11.   urllib2_file:
  12.     Fabien Seisen: <fabien@seisen.org>
  13.  
  14. Example:
  15.   import MultipartPostHandler, urllib2, cookielib
  16.  
  17.   cookies = cookielib.CookieJar()
  18.   opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
  19.                                 MultipartPostHandler.MultipartPostHandler)
  20.   params = { "username" : "bob", "password" : "riviera",
  21.              "file" : open("filename", "rb") }
  22.   opener.open("http://wwww.bobsite.com/upload/", params)
  23.  
  24. Further Example:
  25.   The main function of this file is a sample which downloads a page and
  26.   then uploads it to the W3C validator.
  27. '''
  28. import urllib
  29. import urllib2
  30. import mimetools
  31. import mimetypes
  32. import os
  33. import stat
  34.  
  35. class Callable:
  36.     
  37.     def __init__(self, anycallable):
  38.         self.__call__ = anycallable
  39.  
  40.  
  41. doseq = 1
  42.  
  43. class MultipartPostHandler(urllib2.BaseHandler):
  44.     handler_order = urllib2.HTTPHandler.handler_order - 10
  45.     
  46.     def http_request(self, request):
  47.         data = request.get_data()
  48.         if data is not None and type(data) != str:
  49.             v_files = []
  50.             v_vars = []
  51.             
  52.             try:
  53.                 for key, value in data.items():
  54.                     if type(value) == file:
  55.                         v_files.append((key, value))
  56.                         continue
  57.                     v_vars.append((key, value))
  58.             except TypeError:
  59.                 (systype, value, traceback) = sys.exc_info()
  60.                 raise TypeError, 'not a valid non-string sequence or mapping object', traceback
  61.  
  62.             if len(v_files) == 0:
  63.                 data = urllib.urlencode(v_vars, doseq)
  64.             else:
  65.                 (boundary, data) = self.multipart_encode(v_vars, v_files)
  66.                 contenttype = 'multipart/form-data; boundary=%s' % boundary
  67.                 if request.has_header('Content-Type') and request.get_header('Content-Type').find('multipart/form-data') != 0:
  68.                     print 'Replacing %s with %s' % (request.get_header('content-type'), 'multipart/form-data')
  69.                 
  70.                 request.add_unredirected_header('Content-Type', contenttype)
  71.             request.add_data(data)
  72.         
  73.         return request
  74.  
  75.     
  76.     def multipart_encode(vars, files, boundary = None, buffer = None):
  77.         if boundary is None:
  78.             boundary = mimetools.choose_boundary()
  79.         
  80.         if buffer is None:
  81.             buffer = ''
  82.         
  83.         for key, value in vars:
  84.             buffer += '--%s\r\n' % boundary
  85.             buffer += 'Content-Disposition: form-data; name="%s"' % key
  86.             buffer += '\r\n\r\n' + value + '\r\n'
  87.         
  88.         for key, fd in files:
  89.             file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
  90.             filename = fd.name.split('/')[-1]
  91.             if not mimetypes.guess_type(filename)[0]:
  92.                 pass
  93.             contenttype = 'application/octet-stream'
  94.             buffer += '--%s\r\n' % boundary
  95.             buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
  96.             buffer += 'Content-Type: %s\r\n' % contenttype
  97.             fd.seek(0)
  98.             buffer += '\r\n' + fd.read() + '\r\n'
  99.         
  100.         buffer += '--%s--\r\n\r\n' % boundary
  101.         return (boundary, buffer)
  102.  
  103.     multipart_encode = Callable(multipart_encode)
  104.     https_request = http_request
  105.  
  106.  
  107. def main():
  108.     import tempfile
  109.     import sys
  110.     validatorURL = 'http://validator.w3.org/check'
  111.     opener = urllib2.build_opener(MultipartPostHandler)
  112.     
  113.     def validateFile(url):
  114.         temp = tempfile.mkstemp(suffix = '.html')
  115.         os.write(temp[0], opener.open(url).read())
  116.         params = {
  117.             'ss': '0',
  118.             'doctype': 'Inline',
  119.             'uploaded_file': open(temp[1], 'rb') }
  120.         print opener.open(validatorURL, params).read()
  121.         os.remove(temp[1])
  122.  
  123.     if len(sys.argv[1:]) > 0:
  124.         for arg in sys.argv[1:]:
  125.             validateFile(arg)
  126.         
  127.     else:
  128.         validateFile('http://www.google.com')
  129.  
  130. if __name__ == '__main__':
  131.     main()
  132.  
  133.