MythTV  master
MultipartPostHandler.py
Go to the documentation of this file.
1 #!/usr/bin/python
2 # From http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html
3 
4 
19 """
20 Usage:
21  Enables the use of multipart/form-data for posting forms
22 
23 Inspirations:
24  Upload files in python:
25  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
26  urllib2_file:
27  Fabien Seisen: <fabien@seisen.org>
28 
29 Example:
30  import MultipartPostHandler, urllib2, cookielib
31 
32  cookies = cookielib.CookieJar()
33  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
34  MultipartPostHandler.MultipartPostHandler)
35  params = { "username" : "bob", "password" : "riviera",
36  "file" : open("filename", "rb") }
37  opener.open("http://wwww.bobsite.com/upload/", params)
38 
39 Further Example:
40  The main function of this file is a sample which downloads a page and
41  then uploads it to the W3C validator.
42 """
43 from __future__ import print_function
44 
45 from future import standard_library
46 standard_library.install_aliases()
47 from builtins import object
48 import urllib.request, urllib.error, urllib.parse
49 from email.generator import _make_boundary
50 import mimetypes
51 import os, stat
52 import sys
53 from io import StringIO
54 
55 class Callable(object):
56  def __init__(self, anycallable):
57  self.__call__ = anycallable
58 
59 # Controls how sequences are uncoded. If true, elements may be given multiple values by
60 # assigning a sequence.
61 doseq = 1
62 
63 class MultipartPostHandler(urllib.request.BaseHandler):
64  handler_order = urllib.request.HTTPHandler.handler_order - 10 # needs to run first
65 
66  def http_request(self, request):
67  data = request.data
68  if data is not None and type(data) != str:
69  v_files = []
70  v_vars = []
71  try:
72  for(key, value) in list(data.items()):
73  # 'file' type doesn't exist in python3 and we didn't use it. Removed if:
74  v_vars.append((key, value))
75  except TypeError:
76  systype, value, traceback = sys.exc_info()
77  raise TypeError("not a valid non-string sequence or mapping object", traceback)
78 
79  if len(v_files) == 0:
80  data = urllib.parse.urlencode(v_vars, doseq)
81  else:
82  boundary, data = self.multipart_encode(v_vars, v_files)
83 
84  contenttype = 'multipart/form-data; boundary=%s' % boundary
85  if(request.has_header('Content-Type')
86  and request.get_header('Content-Type').find('multipart/form-data') != 0):
87  print("Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data'))
88  request.add_unredirected_header('Content-Type', contenttype)
89 
90  request.data = bytearray(data, 'latin1')
91 
92  return request
93 
94  def multipart_encode(self, these_vars, files, boundary = None, buf = None):
95  if boundary is None:
96  boundary = _make_boundary(os.getuid + os.getpid())
97  if buf is None:
98  buf = StringIO()
99  for(key, value) in these_vars:
100  buf.write('--%s\r\n' % boundary)
101  buf.write('Content-Disposition: form-data; name="%s"' % key)
102  buf.write('\r\n\r\n' + value + '\r\n')
103  for(key, fd) in files:
104  file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
105  filename = fd.name.split('/')[-1]
106  contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
107  buf.write('--%s\r\n' % boundary)
108  buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
109  buf.write('Content-Type: %s\r\n' % contenttype)
110  # buffer += 'Content-Length: %s\r\n' % file_size
111  fd.seek(0)
112  buf.write('\r\n' + fd.read() + '\r\n')
113  buf.write('--' + boundary + '--\r\n\r\n')
114  buf = buf.getvalue()
115  return boundary, buf
116  multipart_encode = Callable(multipart_encode)
117 
118  https_request = http_request
119 
120 def main():
121  import tempfile, sys
122 
123  validatorURL = "http://validator.w3.org/check"
124  opener = urllib.request.build_opener(MultipartPostHandler)
125 
126  def validateFile(url):
127  temp = tempfile.mkstemp(suffix=".html")
128  os.write(temp[0], opener.open(url).read())
129  params = { "ss" : "0", # show source
130  "doctype" : "Inline",
131  "uploaded_file" : open(temp[1], "rb") }
132  print(opener.open(validatorURL, params).read())
133  os.remove(temp[1])
134 
135  if len(sys.argv[1:]) > 0:
136  for arg in sys.argv[1:]:
137  validateFile(arg)
138  else:
139  validateFile("http://www.google.com")
140 
141 if __name__=="__main__":
142  main()
static void print(const QList< uint > &raw_minimas, const QList< uint > &raw_maximas, const QList< float > &minimas, const QList< float > &maximas)
static pid_list_t::iterator find(const PIDInfoMap &map, pid_list_t &list, pid_list_t::iterator begin, pid_list_t::iterator end, bool find_open)
def read(device=None, features=[])
Definition: disc.py:35