Skip to content
Myr

remove poster

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent ae9cdf1 · Browse files · 3 files+0 added−647 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+0 added−647 removed

  • other:+0 added−647 removed

3 files+0 added−647 removed

deleted:requests/packages/poster/__init__.py-34 removed
1# Copyright (c) 2010 Chris AtLee2# 3# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to deal5# in the Software without restriction, including without limitation the rights6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7# copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:9# 10# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.12# 13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19# THE SOFTWARE.20"""poster module2122Support for streaming HTTP uploads, and multipart/form-data encoding2324```poster.version``` is a 3-tuple of integers representing the version number.25New releases of poster will always have a version number that compares greater26than an older version of poster.27New in version 0.6."""2829from __future__ import absolute_import3031from . import streaminghttp32from . import encode3334version = (0, 8, 0) # Thanks JP!
deleted:requests/packages/poster/encode.py-414 removed
1"""multipart/form-data encoding module23This module provides functions that faciliate encoding name/value pairs4as multipart/form-data suitable for a HTTP POST or PUT request.56multipart/form-data is the standard way to upload files over HTTP"""78__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',9 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',10 'multipart_encode']1112try:13 import uuid14 def gen_boundary():15 """Returns a random string to use as the boundary for a message"""16 return uuid.uuid4().hex17except ImportError:18 import random, sha19 def gen_boundary():20 """Returns a random string to use as the boundary for a message"""21 bits = random.getrandbits(160)22 return sha.new(str(bits)).hexdigest()2324import urllib, re, os, mimetypes25try:26 from email.header import Header27except ImportError:28 # Python 2.429 from email.Header import Header3031def encode_and_quote(data):32 """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))33 otherwise return urllib.quote_plus(data)"""34 if data is None:35 return None3637 if isinstance(data, unicode):38 data = data.encode("utf-8")39 return urllib.quote_plus(data)4041def _strify(s):42 """If s is a unicode string, encode it to UTF-8 and return the results,43 otherwise return str(s), or None if s is None"""44 if s is None:45 return None46 if isinstance(s, unicode):47 return s.encode("utf-8")48 return str(s)4950class MultipartParam(object):51 """Represents a single parameter in a multipart/form-data request5253 ``name`` is the name of this parameter.5455 If ``value`` is set, it must be a string or unicode object to use as the56 data for this parameter.5758 If ``filename`` is set, it is what to say that this parameter's filename59 is. Note that this does not have to be the actual filename any local file.6061 If ``filetype`` is set, it is used as the Content-Type for this parameter.62 If unset it defaults to "text/plain; charset=utf8"6364 If ``filesize`` is set, it specifies the length of the file ``fileobj``6566 If ``fileobj`` is set, it must be a file-like object that supports67 .read().6869 Both ``value`` and ``fileobj`` must not be set, doing so will70 raise a ValueError assertion.7172 If ``fileobj`` is set, and ``filesize`` is not specified, then73 the file's size will be determined first by stat'ing ``fileobj``'s74 file descriptor, and if that fails, by seeking to the end of the file,75 recording the current position as the size, and then by seeking back to the76 beginning of the file.7778 ``cb`` is a callable which will be called from iter_encode with (self,79 current, total), representing the current parameter, current amount80 transferred, and the total size.81 """82 def __init__(self, name, value=None, filename=None, filetype=None,83 filesize=None, fileobj=None, cb=None):84 self.name = Header(name).encode()85 self.value = _strify(value)86 if filename is None:87 self.filename = None88 else:89 if isinstance(filename, unicode):90 # Encode with XML entities91 self.filename = filename.encode("ascii", "xmlcharrefreplace")92 else:93 self.filename = str(filename)94 self.filename = self.filename.encode("string_escape").\95 replace('"', '\\"')96 self.filetype = _strify(filetype)9798 self.filesize = filesize99 self.fileobj = fileobj100 self.cb = cb101102 if self.value is not None and self.fileobj is not None:103 raise ValueError("Only one of value or fileobj may be specified")104105 if fileobj is not None and filesize is None:106 # Try and determine the file size107 try:108 self.filesize = os.fstat(fileobj.fileno()).st_size109 except (OSError, AttributeError):110 try:111 fileobj.seek(0, 2)112 self.filesize = fileobj.tell()113 fileobj.seek(0)114 except:115 raise ValueError("Could not determine filesize")116117 def __cmp__(self, other):118 attrs = ['name', 'value', 'filename', 'filetype', 'filesize', 'fileobj']119 myattrs = [getattr(self, a) for a in attrs]120 oattrs = [getattr(other, a) for a in attrs]121 return cmp(myattrs, oattrs)122123 def reset(self):124 if self.fileobj is not None:125 self.fileobj.seek(0)126 elif self.value is None:127 raise ValueError("Don't know how to reset this parameter")128129 @classmethod130 def from_file(cls, paramname, filename):131 """Returns a new MultipartParam object constructed from the local132 file at ``filename``.133134 ``filesize`` is determined by os.path.getsize(``filename``)135136 ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]137138 ``filename`` is set to os.path.basename(``filename``)139 """140141 return cls(paramname, filename=os.path.basename(filename),142 filetype=mimetypes.guess_type(filename)[0],143 filesize=os.path.getsize(filename),144 fileobj=open(filename, "rb"))145146 @classmethod147 def from_params(cls, params):148 """Returns a list of MultipartParam objects from a sequence of149 name, value pairs, MultipartParam instances,150 or from a mapping of names to values151152 The values may be strings or file objects, or MultipartParam objects.153 MultipartParam object names must match the given names in the154 name,value pairs or mapping, if applicable."""155 if hasattr(params, 'items'):156 params = params.items()157158 retval = []159 for item in params:160 if isinstance(item, cls):161 retval.append(item)162 continue163 name, value = item164 if isinstance(value, cls):165 assert value.name == name166 retval.append(value)167 continue168 if hasattr(value, 'read'):169 # Looks like a file object170 filename = getattr(value, 'name', None)171 if filename is not None:172 filetype = mimetypes.guess_type(filename)[0]173 else:174 filetype = None175176 retval.append(cls(name=name, filename=filename,177 filetype=filetype, fileobj=value))178 else:179 retval.append(cls(name, value))180 return retval181182 def encode_hdr(self, boundary):183 """Returns the header of the encoding of this parameter"""184 boundary = encode_and_quote(boundary)185186 headers = ["--%s" % boundary]187188 if self.filename:189 disposition = 'form-data; name="%s"; filename="%s"' % (self.name,190 self.filename)191 else:192 disposition = 'form-data; name="%s"' % self.name193194 headers.append("Content-Disposition: %s" % disposition)195196 if self.filetype:197 filetype = self.filetype198 else:199 filetype = "text/plain; charset=utf-8"200201 headers.append("Content-Type: %s" % filetype)202203 headers.append("")204 headers.append("")205206 return "\r\n".join(headers)207208 def encode(self, boundary):209 """Returns the string encoding of this parameter"""210 if self.value is None:211 value = self.fileobj.read()212 else:213 value = self.value214215 if re.search("^--%s$" % re.escape(boundary), value, re.M):216 raise ValueError("boundary found in encoded string")217218 return "%s%s\r\n" % (self.encode_hdr(boundary), value)219220 def iter_encode(self, boundary, blocksize=4096):221 """Yields the encoding of this parameter222 If self.fileobj is set, then blocks of ``blocksize`` bytes are read and223 yielded."""224 total = self.get_size(boundary)225 current = 0226 if self.value is not None:227 block = self.encode(boundary)228 current += len(block)229 yield block230 if self.cb:231 self.cb(self, current, total)232 else:233 block = self.encode_hdr(boundary)234 current += len(block)235 yield block236 if self.cb:237 self.cb(self, current, total)238 last_block = ""239 encoded_boundary = "--%s" % encode_and_quote(boundary)240 boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),241 re.M)242 while True:243 block = self.fileobj.read(blocksize)244 if not block:245 current += 2246 yield "\r\n"247 if self.cb:248 self.cb(self, current, total)249 break250 last_block += block251 if boundary_exp.search(last_block):252 raise ValueError("boundary found in file data")253 last_block = last_block[-len(encoded_boundary)-2:]254 current += len(block)255 yield block256 if self.cb:257 self.cb(self, current, total)258259 def get_size(self, boundary):260 """Returns the size in bytes that this param will be when encoded261 with the given boundary."""262 if self.filesize is not None:263 valuesize = self.filesize264 else:265 valuesize = len(self.value)266267 return len(self.encode_hdr(boundary)) + 2 + valuesize268269def encode_string(boundary, name, value):270 """Returns ``name`` and ``value`` encoded as a multipart/form-data271 variable. ``boundary`` is the boundary string used throughout272 a single request to separate variables."""273274 return MultipartParam(name, value).encode(boundary)275276def encode_file_header(boundary, paramname, filesize, filename=None,277 filetype=None):278 """Returns the leading data for a multipart/form-data field that contains279 file data.280281 ``boundary`` is the boundary string used throughout a single request to282 separate variables.283284 ``paramname`` is the name of the variable in this request.285286 ``filesize`` is the size of the file data.287288 ``filename`` if specified is the filename to give to this field. This289 field is only useful to the server for determining the original filename.290291 ``filetype`` if specified is the MIME type of this file.292293 The actual file data should be sent after this header has been sent.294 """295296 return MultipartParam(paramname, filesize=filesize, filename=filename,297 filetype=filetype).encode_hdr(boundary)298299def get_body_size(params, boundary):300 """Returns the number of bytes that the multipart/form-data encoding301 of ``params`` will be."""302 size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))303 return size + len(boundary) + 6304305def get_headers(params, boundary):306 """Returns a dictionary with Content-Type and Content-Length headers307 for the multipart/form-data encoding of ``params``."""308 headers = {}309 boundary = urllib.quote_plus(boundary)310 headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary311 headers['Content-Length'] = str(get_body_size(params, boundary))312 return headers313314class multipart_yielder:315 def __init__(self, params, boundary, cb):316 self.params = params317 self.boundary = boundary318 self.cb = cb319320 self.i = 0321 self.p = None322 self.param_iter = None323 self.current = 0324 self.total = get_body_size(params, boundary)325326 def __iter__(self):327 return self328329 def next(self):330 """generator function to yield multipart/form-data representation331 of parameters"""332 if self.param_iter is not None:333 try:334 block = self.param_iter.next()335 self.current += len(block)336 if self.cb:337 self.cb(self.p, self.current, self.total)338 return block339 except StopIteration:340 self.p = None341 self.param_iter = None342343 if self.i is None:344 raise StopIteration345 elif self.i >= len(self.params):346 self.param_iter = None347 self.p = None348 self.i = None349 block = "--%s--\r\n" % self.boundary350 self.current += len(block)351 if self.cb:352 self.cb(self.p, self.current, self.total)353 return block354355 self.p = self.params[self.i]356 self.param_iter = self.p.iter_encode(self.boundary)357 self.i += 1358 return self.next()359360 def reset(self):361 self.i = 0362 self.current = 0363 for param in self.params:364 param.reset()365366def multipart_encode(params, boundary=None, cb=None):367 """Encode ``params`` as multipart/form-data.368369 ``params`` should be a sequence of (name, value) pairs or MultipartParam370 objects, or a mapping of names to values.371 Values are either strings parameter values, or file-like objects to use as372 the parameter value. The file-like objects must support .read() and either373 .fileno() or both .seek() and .tell().374375 If ``boundary`` is set, then it as used as the MIME boundary. Otherwise376 a randomly generated boundary will be used. In either case, if the377 boundary string appears in the parameter values a ValueError will be378 raised.379380 If ``cb`` is set, it should be a callback which will get called as blocks381 of data are encoded. It will be called with (param, current, total),382 indicating the current parameter being encoded, the current amount encoded,383 and the total amount to encode.384385 Returns a tuple of `datagen`, `headers`, where `datagen` is a386 generator that will yield blocks of data that make up the encoded387 parameters, and `headers` is a dictionary with the assoicated388 Content-Type and Content-Length headers.389390 Examples:391392 >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )393 >>> s = "".join(datagen)394 >>> assert "value2" in s and "value1" in s395396 >>> p = MultipartParam("key", "value2")397 >>> datagen, headers = multipart_encode( [("key", "value1"), p] )398 >>> s = "".join(datagen)399 >>> assert "value2" in s and "value1" in s400401 >>> datagen, headers = multipart_encode( {"key": "value1"} )402 >>> s = "".join(datagen)403 >>> assert "value2" not in s and "value1" in s404405 """406 if boundary is None:407 boundary = gen_boundary()408 else:409 boundary = urllib.quote_plus(boundary)410411 headers = get_headers(params, boundary)412 params = MultipartParam.from_params(params)413414 return multipart_yielder(params, boundary, cb), headers
deleted:requests/packages/poster/streaminghttp.py-199 removed
1"""Streaming HTTP uploads module.23This module extends the standard httplib and urllib2 objects so that4iterable objects can be used in the body of HTTP requests.56In most cases all one should have to do is call :func:`register_openers()`7to register the new streaming http handlers which will take priority over8the default handlers, and then you can use iterable objects in the body9of HTTP requests.1011**N.B.** You must specify a Content-Length header if using an iterable object12since there is no way to determine in advance the total size that will be13yielded, and there is no way to reset an interator.1415Example usage:1617>>> from StringIO import StringIO18>>> import urllib2, poster.streaminghttp1920>>> opener = poster.streaminghttp.register_openers()2122>>> s = "Test file data"23>>> f = StringIO(s)2425>>> req = urllib2.Request("http://localhost:5000", f,26... {'Content-Length': str(len(s))})27"""2829import httplib, urllib2, socket30from httplib import NotConnected3132__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',33 'StreamingHTTPHandler', 'register_openers']3435if hasattr(httplib, 'HTTPS'):36 __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])3738class _StreamingHTTPMixin:39 """Mixin class for HTTP and HTTPS connections that implements a streaming40 send method."""41 def send(self, value):42 """Send ``value`` to the server.4344 ``value`` can be a string object, a file-like object that supports45 a .read() method, or an iterable object that supports a .next()46 method.47 """48 # Based on python 2.6's httplib.HTTPConnection.send()49 if self.sock is None:50 if self.auto_open:51 self.connect()52 else:53 raise NotConnected()5455 # send the data to the server. if we get a broken pipe, then close56 # the socket. we want to reconnect when somebody tries to send again.57 #58 # NOTE: we DO propagate the error, though, because we cannot simply59 # ignore the error... the caller will know if they can retry.60 if self.debuglevel > 0:61 print "send:", repr(value)62 try:63 blocksize = 819264 if hasattr(value, 'read') :65 if hasattr(value, 'seek'):66 value.seek(0)67 if self.debuglevel > 0:68 print "sendIng a read()able"69 data = value.read(blocksize)70 while data:71 self.sock.sendall(data)72 data = value.read(blocksize)73 elif hasattr(value, 'next'):74 if hasattr(value, 'reset'):75 value.reset()76 if self.debuglevel > 0:77 print "sendIng an iterable"78 for data in value:79 self.sock.sendall(data)80 else:81 self.sock.sendall(value)82 except socket.error, v:83 if v[0] == 32: # Broken pipe84 self.close()85 raise8687class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):88 """Subclass of `httplib.HTTPConnection` that overrides the `send()` method89 to support iterable body objects"""9091class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):92 """Subclass of `urllib2.HTTPRedirectHandler` that overrides the93 `redirect_request` method to properly handle redirected POST requests9495 This class is required because python 2.5's HTTPRedirectHandler does96 not remove the Content-Type or Content-Length headers when requesting97 the new resource, but the body of the original request is not preserved.98 """99100 handler_order = urllib2.HTTPRedirectHandler.handler_order - 1101102 # From python2.6 urllib2's HTTPRedirectHandler103 def redirect_request(self, req, fp, code, msg, headers, newurl):104 """Return a Request or None in response to a redirect.105106 This is called by the http_error_30x methods when a107 redirection response is received. If a redirection should108 take place, return a new Request to allow http_error_30x to109 perform the redirect. Otherwise, raise HTTPError if no-one110 else should try to handle this url. Return None if you can't111 but another Handler might.112 """113 m = req.get_method()114 if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")115 or code in (301, 302, 303) and m == "POST"):116 # Strictly (according to RFC 2616), 301 or 302 in response117 # to a POST MUST NOT cause a redirection without confirmation118 # from the user (of urllib2, in this case). In practice,119 # essentially all clients do redirect in this case, so we120 # do the same.121 # be conciliant with URIs containing a space122 newurl = newurl.replace(' ', '%20')123 newheaders = dict((k, v) for k, v in req.headers.items()124 if k.lower() not in (125 "content-length", "content-type")126 )127 return urllib2.Request(newurl,128 headers=newheaders,129 origin_req_host=req.get_origin_req_host(),130 unverifiable=True)131 else:132 raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)133134class StreamingHTTPHandler(urllib2.HTTPHandler):135 """Subclass of `urllib2.HTTPHandler` that uses136 StreamingHTTPConnection as its http connection class."""137138 handler_order = urllib2.HTTPHandler.handler_order - 1139140 def http_open(self, req):141 """Open a StreamingHTTPConnection for the given request"""142 return self.do_open(StreamingHTTPConnection, req)143144 def http_request(self, req):145 """Handle a HTTP request. Make sure that Content-Length is specified146 if we're using an interable value"""147 # Make sure that if we're using an iterable object as the request148 # body, that we've also specified Content-Length149 if req.has_data():150 data = req.get_data()151 if hasattr(data, 'read') or hasattr(data, 'next'):152 if not req.has_header('Content-length'):153 raise ValueError(154 "No Content-Length specified for iterable body")155 return urllib2.HTTPHandler.do_request_(self, req)156157if hasattr(httplib, 'HTTPS'):158 class StreamingHTTPSConnection(_StreamingHTTPMixin,159 httplib.HTTPSConnection):160 """Subclass of `httplib.HTTSConnection` that overrides the `send()`161 method to support iterable body objects"""162163 class StreamingHTTPSHandler(urllib2.HTTPSHandler):164 """Subclass of `urllib2.HTTPSHandler` that uses165 StreamingHTTPSConnection as its http connection class."""166167 handler_order = urllib2.HTTPSHandler.handler_order - 1168169 def https_open(self, req):170 return self.do_open(StreamingHTTPSConnection, req)171172 def https_request(self, req):173 # Make sure that if we're using an iterable object as the request174 # body, that we've also specified Content-Length175 if req.has_data():176 data = req.get_data()177 if hasattr(data, 'read') or hasattr(data, 'next'):178 if not req.has_header('Content-length'):179 raise ValueError(180 "No Content-Length specified for iterable body")181 return urllib2.HTTPSHandler.do_request_(self, req)182183184def get_handlers():185 handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186 if hasattr(httplib, "HTTPS"):187 handlers.append(StreamingHTTPSHandler)188 return handlers189 190def register_openers():191 """Register the streaming http handlers in the global urllib2 default192 opener object.193194 Returns the created OpenerDirector object."""195 opener = urllib2.build_opener(*get_handlers())196197 urllib2.install_opener(opener)198199 return opener