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