desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Calls __getattr__ on the remote object and returns the attribute by value or by proxy depending on the options set (see ObjectProxy._setProxyOptions and RemoteEventHandler.setProxyOptions) If the option \'deferGetattr\' is True for this proxy, then a new proxy object is returned _without_ asking the remote object whether the named attribute exists. This can save time when making multiple chained attribute requests, but may also defer a possible AttributeError until later, making them more difficult to debug.'
def __getattr__(self, attr, **kwds):
opts = self._getProxyOptions() for k in opts: if (('_' + k) in kwds): opts[k] = kwds.pop(('_' + k)) if (opts['deferGetattr'] is True): return self._deferredAttr(attr) else: return self._handler.getObjAttr(self, attr, **opts)
'Attempts to call the proxied object from the remote process. Accepts extra keyword arguments: _callSync \'off\', \'sync\', or \'async\' _returnType \'value\', \'proxy\', or \'auto\' If the remote call raises an exception on the remote process, it will be re-raised on the local process.'
def __call__(self, *args, **kwds):
opts = self._getProxyOptions() for k in opts: if (('_' + k) in kwds): opts[k] = kwds.pop(('_' + k)) return self._handler.callObj(obj=self, args=args, kwds=kwds, **opts)
'Return a non-deferred ObjectProxy referencing the same object'
def _undefer(self):
return self._parent.__getattr__(self._attributes[(-1)], _deferGetattr=False)
'**Arguments:** tasks list of objects to be processed (Parallelize will determine how to distribute the tasks). If unspecified, then each worker will receive a single task with a unique id number. workers number of worker processes or None to use number of CPUs in the system progressDialog optional dict of arguments for ProgressDialog to update while tasks are processed randomReseed If True, each forked process will reseed its random number generator to ensure independent results. Works with the built-in random and numpy.random. kwds objects to be shared by proxy with child processes (they will appear as attributes of the tasker)'
def __init__(self, tasks=None, workers=None, block=True, progressDialog=None, randomReseed=True, **kwds):
self.showProgress = False if (progressDialog is not None): self.showProgress = True if isinstance(progressDialog, basestring): progressDialog = {'labelText': progressDialog} from ..widgets.ProgressDialog import ProgressDialog self.progressDlg = ProgressDialog(**progressDialog) if (workers is None): workers = self.suggestedWorkerCount() if (not hasattr(os, 'fork')): workers = 1 self.workers = workers if (tasks is None): tasks = range(workers) self.tasks = list(tasks) self.reseed = randomReseed self.kwds = kwds.copy() self.kwds['_taskStarted'] = self._taskStarted
'Process requests from parent. Usually it is not necessary to call this unless you would like to receive messages (such as exit requests) during an iteration.'
def process(self):
if (self.proc is not None): self.proc.processRequests()
'Return the number of parallel workers'
def numWorkers(self):
return self.par.workers
'Return (angle, axis) of rotation'
def getRotation(self):
return (self._state['angle'], Vector(self._state['axis']))
'Adjust the translation of this transform'
def translate(self, *args):
t = Vector(*args) self.setTranslate((self._state['pos'] + t))
'Set the translation of this transform'
def setTranslate(self, *args):
self._state['pos'] = Vector(*args) self.update()
'adjust the scale of this transform'
def scale(self, *args):
if ((len(args) == 1) and hasattr(args[0], '__len__')): args = args[0] if (len(args) == 2): args = (args + (1,)) s = Vector(*args) self.setScale((self._state['scale'] * s))
'Set the scale of this transform'
def setScale(self, *args):
if ((len(args) == 1) and hasattr(args[0], '__len__')): args = args[0] if (len(args) == 2): args = (args + (1,)) self._state['scale'] = Vector(*args) self.update()
'Adjust the rotation of this transform'
def rotate(self, angle, axis=(0, 0, 1)):
origAxis = self._state['axis'] if ((axis[0] == origAxis[0]) and (axis[1] == origAxis[1]) and (axis[2] == origAxis[2])): self.setRotate((self._state['angle'] + angle)) else: m = QtGui.QMatrix4x4() m.translate(*self._state['pos']) m.rotate(self._state['angle'], *self._state['axis']) m.rotate(angle, *axis) m.scale(*self._state['scale']) self.setFromMatrix(m)
'Set the transformation rotation to angle (in degrees)'
def setRotate(self, angle, axis=(0, 0, 1)):
self._state['angle'] = angle self._state['axis'] = Vector(axis) self.update()
'Set this transform mased on the elements of *m* The input matrix must be affine AND have no shear, otherwise the conversion will most likely fail.'
def setFromMatrix(self, m):
import numpy.linalg for i in range(4): self.setRow(i, m.row(i)) m = self.matrix().reshape(4, 4) self._state['pos'] = m[:3, 3] scale = ((m[:3, :3] ** 2).sum(axis=0) ** 0.5) z = np.cross(m[0, :3], m[1, :3]) if (np.dot(z, m[2, :3]) < 0): scale[1] *= (-1) self._state['scale'] = scale r = (m[:3, :3] / scale[np.newaxis, :]) try: (evals, evecs) = numpy.linalg.eig(r) except: print ('Rotation matrix: %s' % str(r)) print ('Scale: %s' % str(scale)) print ('Original matrix: %s' % str(m)) raise eigIndex = np.argwhere((np.abs((evals - 1)) < 1e-06)) if (len(eigIndex) < 1): print ('eigenvalues: %s' % str(evals)) print ('eigenvectors: %s' % str(evecs)) print ('index: %s, %s' % (str(eigIndex), str((evals - 1)))) raise Exception('Could not determine rotation axis.') axis = evecs[:, eigIndex[(0, 0)]].real axis /= ((axis ** 2).sum() ** 0.5) self._state['axis'] = axis cos = ((r.trace() - 1) * 0.5) axisInd = np.argmax(np.abs(axis)) (rInd, sign) = [((1, 2), (-1)), ((0, 2), 1), ((0, 1), (-1))][axisInd] sin = ((r - r.T)[rInd] / ((2.0 * sign) * axis[axisInd])) self._state['angle'] = ((np.arctan2(sin, cos) * 180) / np.pi) if (self._state['angle'] == 0): self._state['axis'] = (0, 0, 1)
'Return a QTransform representing the x,y portion of this transform (if possible)'
def as2D(self):
return SRTTransform(self)
'Used to register Exporter classes to appear in the export dialog.'
@classmethod def register(cls):
Exporter.Exporters.append(cls)
'Initialize with the item to be exported. Can be an individual graphics item or a scene.'
def __init__(self, item):
object.__init__(self) self.item = item
'Return the parameters used to configure this exporter.'
def parameters(self):
raise Exception('Abstract method must be overridden in subclass.')
'If *fileName* is None, pop-up a file dialog. If *toBytes* is True, return a bytes object rather than writing to file. If *copy* is True, export to the copy buffer rather than writing to file.'
def export(self, fileName=None, toBytes=False, copy=False):
raise Exception('Abstract method must be overridden in subclass.')
'Call setExportMode(export, opts) on all items that will be painted during the export. This informs the item that it is about to be painted for export, allowing it to alter its appearance temporarily *export* - bool; must be True before exporting and False afterward *opts* - dict; common parameters are \'antialias\' and \'background\''
def setExportMode(self, export, opts=None):
if (opts is None): opts = {} for item in self.getPaintItems(): if hasattr(item, 'setExportMode'): item.setExportMode(export, opts)
'Return a list of all items that should be painted in the correct order.'
def getPaintItems(self, root=None):
if (root is None): root = self.item preItems = [] postItems = [] if isinstance(root, QtGui.QGraphicsScene): childs = [i for i in root.items() if (i.parentItem() is None)] rootItem = [] else: childs = root.childItems() rootItem = [root] childs.sort(key=(lambda a: a.zValue())) while (len(childs) > 0): ch = childs.pop(0) tree = self.getPaintItems(ch) if ((int((ch.flags() & ch.ItemStacksBehindParent)) > 0) or ((ch.zValue() < 0) and (int((ch.flags() & ch.ItemNegativeZStacksBehindParent)) > 0))): preItems.extend(tree) else: postItems.extend(tree) return ((preItems + rootItem) + postItems)
'Return the index of refraction for *glass* at wavelength *wl*. The *glass* argument must be a key in self.data.'
def ior(self, glass, wl):
info = self.data[glass] cache = info['ior_cache'] if (wl not in cache): B = list(map(float, [info['B1'], info['B2'], info['B3']])) C = list(map(float, [info['C1'], info['C2'], info['C3']])) w2 = ((wl / 1000.0) ** 2) n = np.sqrt((((1.0 + ((B[0] * w2) / (w2 - C[0]))) + ((B[1] * w2) / (w2 - C[1]))) + ((B[2] * w2) / (w2 - C[2])))) cache[wl] = n return cache[wl]
'Set parameters for this optic. This is a good function to override for subclasses.'
def setParams(self, **params):
self.__params.update(params) self.paramStateChanged()
'Some parameters of the optic have changed.'
def paramStateChanged(self):
self.gitem.setPos(Point(self['pos'])) self.gitem.resetTransform() self.gitem.rotate(self['angle']) try: self.roi.sigRegionChanged.disconnect(self.roiChanged) br = self.gitem.boundingRect() o = self.gitem.mapToParent(br.topLeft()) self.roi.setAngle(self['angle']) self.roi.setPos(o) self.roi.setSize([br.width(), br.height()]) finally: self.roi.sigRegionChanged.connect(self.roiChanged) self.sigStateChanged.emit()
'Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays'
def propagateRay(self, ray):
'\n NOTE:: We can probably use this to compute refractions faster: (from GLSL 120 docs)\n\n For the incident vector I and surface normal N, and the\n ratio of indices of refraction eta, return the refraction\n vector. The result is computed by\n k = 1.0 - eta * eta * (1.0 - dot(N, I) * dot(N, I))\n if (k < 0.0)\n return genType(0.0)\n else\n return eta * I - (eta * dot(N, I) + sqrt(k)) * N\n The input parameters for the incident vector I and the\n surface normal N must already be normalized to get the\n desired results. eta == ratio of IORs\n\n\n For reflection:\n For the incident vector I and surface orientation N,\n returns the reflection direction:\n I \xe2\x80\x93 2 \xe2\x88\x97 dot(N, I) \xe2\x88\x97 N\n N must already be normalized in order to achieve the\n desired result.\n ' iors = [self.ior(ray['wl']), 1.0] for i in [0, 1]: surface = self.surfaces[i] ior = iors[i] (p1, ai) = surface.intersectRay(ray) if (p1 is None): ray.setEnd(None) break p1 = surface.mapToItem(ray, p1) rd = ray['dir'] a1 = np.arctan2(rd[1], rd[0]) ar = ((a1 - ai) + np.arcsin(((np.sin(ai) * ray['ior']) / ior))) ray.setEnd(p1) dp = Point(np.cos(ar), np.sin(ar)) ray = Ray(parent=ray, ior=ior, dir=dp) return [ray]
'Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays'
def propagateRay(self, ray):
surface = self.surfaces[0] (p1, ai) = surface.intersectRay(ray) if (p1 is not None): p1 = surface.mapToItem(ray, p1) rd = ray['dir'] a1 = np.arctan2(rd[1], rd[0]) ar = ((a1 + np.pi) - (2 * ai)) ray.setEnd(p1) dp = Point(np.cos(ar), np.sin(ar)) ray = Ray(parent=ray, dir=dp) else: ray.setEnd(None) return [ray]
'Arguments for each surface are: x1,x2 - position of center of _physical surface_ r1,r2 - radius of curvature d1,d2 - diameter of optic'
def __init__(self, pen=None, brush=None, **opts):
defaults = dict(x1=(-2), r1=100, d1=25.4, x2=2, r2=100, d2=25.4) defaults.update(opts) ParamObj.__init__(self) self.surfaces = [CircleSurface(defaults['r1'], defaults['d1']), CircleSurface((- defaults['r2']), defaults['d2'])] pg.GraphicsObject.__init__(self) for s in self.surfaces: s.setParentItem(self) if (pen is None): self.pen = pg.mkPen((220, 220, 255, 200), width=1, cosmetic=True) else: self.pen = pg.mkPen(pen) if (brush is None): self.brush = pg.mkBrush((230, 230, 255, 30)) else: self.brush = pg.mkBrush(brush) self.setParams(**defaults)
'center of physical surface is at 0,0 radius is the radius of the surface. If radius is None, the surface is flat. diameter is of the optic\'s edge.'
def __init__(self, radius=None, diameter=None):
pg.GraphicsObject.__init__(self) self.r = radius self.d = diameter self.mkPath()
'cookielib has no legitimate use for this method; add it back if you find one.'
def add_header(self, key, val):
raise NotImplementedError('Cookie headers should be added with add_unredirected_header()')
'Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers'
def __init__(self, headers):
self._headers = headers
'Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1).'
def get(self, name, default=None, domain=None, path=None):
try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
'Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.'
def set(self, name, value, **kwargs):
if (value is None): remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c
'Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems().'
def iterkeys(self):
for cookie in iter(self): (yield cookie.name)
'Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items().'
def keys(self):
return list(self.iterkeys())
'Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems().'
def itervalues(self):
for cookie in iter(self): (yield cookie.value)
'Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items().'
def values(self):
return list(self.itervalues())
'Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues().'
def iteritems(self):
for cookie in iter(self): (yield (cookie.name, cookie.value))
'Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values().'
def items(self):
return list(self.iteritems())
'Utility method to list all the domains in the jar.'
def list_domains(self):
domains = [] for cookie in iter(self): if (cookie.domain not in domains): domains.append(cookie.domain) return domains
'Utility method to list all the paths in the jar.'
def list_paths(self):
paths = [] for cookie in iter(self): if (cookie.path not in paths): paths.append(cookie.path) return paths
'Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool'
def multiple_domains(self):
domains = [] for cookie in iter(self): if ((cookie.domain is not None) and (cookie.domain in domains)): return True domains.append(cookie.domain) return False
'Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. :rtype: dict'
def get_dict(self, domain=None, path=None):
dictionary = {} for cookie in iter(self): if (((domain is None) or (cookie.domain == domain)) and ((path is None) or (cookie.path == path))): dictionary[cookie.name] = cookie.value return dictionary
'Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1).'
def __getitem__(self, name):
return self._find_no_duplicates(name)
'Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead.'
def __setitem__(self, name, value):
self.set(name, value)
'Deletes a cookie given a name. Wraps ``cookielib.CookieJar``\'s ``remove_cookie_by_name()``.'
def __delitem__(self, name):
remove_cookie_by_name(self, name)
'Updates this jar with cookies from another CookieJar or dict-like'
def update(self, other):
if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super(RequestsCookieJar, self).update(other)
'Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value'
def _find(self, name, domain=None, path=None):
for cookie in iter(self): if (cookie.name == name): if ((domain is None) or (cookie.domain == domain)): if ((path is None) or (cookie.path == path)): return cookie.value raise KeyError(('name=%r, domain=%r, path=%r' % (name, domain, path)))
'Both ``__get_item__`` and ``get`` call this function: it\'s never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value'
def _find_no_duplicates(self, name, domain=None, path=None):
toReturn = None for cookie in iter(self): if (cookie.name == name): if ((domain is None) or (cookie.domain == domain)): if ((path is None) or (cookie.path == path)): if (toReturn is not None): raise CookieConflictError(('There are multiple cookies with name, %r' % name)) toReturn = cookie.value if toReturn: return toReturn raise KeyError(('name=%r, domain=%r, path=%r' % (name, domain, path)))
'Unlike a normal CookieJar, this class is pickleable.'
def __getstate__(self):
state = self.__dict__.copy() state.pop('_cookies_lock') return state
'Unlike a normal CookieJar, this class is pickleable.'
def __setstate__(self, state):
self.__dict__.update(state) if ('_cookies_lock' not in self.__dict__): self._cookies_lock = threading.RLock()
'Return a copy of this RequestsCookieJar.'
def copy(self):
new_cj = RequestsCookieJar() new_cj.update(self) return new_cj
'Initialize RequestException with `request` and `response` objects.'
def __init__(self, *args, **kwargs):
response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) if ((response is not None) and (not self.request) and hasattr(response, 'request')): self.request = self.response.request super(RequestException, self).__init__(*args, **kwargs)
'Build the path URL to use.'
@property def path_url(self):
url = [] p = urlsplit(self.url) path = p.path if (not path): path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url)
'Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.'
@staticmethod def _encode_params(data):
if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for (k, vs) in to_key_val_list(data): if (isinstance(vs, basestring) or (not hasattr(vs, '__iter__'))): vs = [vs] for v in vs: if (v is not None): result.append(((k.encode('utf-8') if isinstance(k, str) else k), (v.encode('utf-8') if isinstance(v, str) else v))) return urlencode(result, doseq=True) else: return data
'Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).'
@staticmethod def _encode_files(files, data):
if (not files): raise ValueError('Files must be provided.') elif isinstance(data, basestring): raise ValueError('Data must not be a string.') new_fields = [] fields = to_key_val_list((data or {})) files = to_key_val_list((files or {})) for (field, val) in fields: if (isinstance(val, basestring) or (not hasattr(val, '__iter__'))): val = [val] for v in val: if (v is not None): if (not isinstance(v, bytes)): v = str(v) new_fields.append(((field.decode('utf-8') if isinstance(field, bytes) else field), (v.encode('utf-8') if isinstance(v, str) else v))) for (k, v) in files: ft = None fh = None if isinstance(v, (tuple, list)): if (len(v) == 2): (fn, fp) = v elif (len(v) == 3): (fn, fp, ft) = v else: (fn, fp, ft, fh) = v else: fn = (guess_filename(v) or k) fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp else: fdata = fp.read() rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) (body, content_type) = encode_multipart_formdata(new_fields) return (body, content_type)
'Properly register a hook.'
def register_hook(self, event, hook):
if (event not in self.hooks): raise ValueError(('Unsupported event specified, with event name "%s"' % event)) if isinstance(hook, collections.Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend((h for h in hook if isinstance(h, collections.Callable)))
'Deregister a previously registered hook. Returns True if the hook existed, False if not.'
def deregister_hook(self, event, hook):
try: self.hooks[event].remove(hook) return True except ValueError: return False
'Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.'
def prepare(self):
p = PreparedRequest() p.prepare(method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks) return p
'Prepares the entire request with the given parameters.'
def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None):
self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) self.prepare_hooks(hooks)
'Prepares the given HTTP method.'
def prepare_method(self, method):
self.method = method if (self.method is not None): self.method = to_native_string(self.method.upper())
'Prepares the given HTTP URL.'
def prepare_url(self, url, params):
if isinstance(url, bytes): url = url.decode('utf8') else: url = (unicode(url) if is_py2 else str(url)) url = url.lstrip() if ((':' in url) and (not url.lower().startswith('http'))): self.url = url return try: (scheme, auth, host, port, path, query, fragment) = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if (not scheme): error = 'Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?' error = error.format(to_native_string(url, 'utf8')) raise MissingSchema(error) if (not host): raise InvalidURL(('Invalid URL %r: No host supplied' % url)) if (not unicode_is_ascii(host)): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL('URL has an invalid label.') elif host.startswith(u'*'): raise InvalidURL('URL has an invalid label.') netloc = (auth or '') if netloc: netloc += '@' netloc += host if port: netloc += (':' + str(port)) if (not path): path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = ('%s&%s' % (query, enc_params)) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url
'Prepares the given HTTP headers.'
def prepare_headers(self, headers):
self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): check_header_validity(header) (name, value) = header self.headers[to_native_string(name)] = value
'Prepares the given HTTP body data.'
def prepare_body(self, data, files, json=None):
body = None content_type = None if ((not data) and (json is not None)): content_type = 'application/json' body = complexjson.dumps(json) if (not isinstance(body, bytes)): body = body.encode('utf-8') is_stream = all([hasattr(data, '__iter__'), (not isinstance(data, (basestring, list, tuple, collections.Mapping)))]) try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None if is_stream: body = data if (getattr(body, 'tell', None) is not None): try: self._body_position = body.tell() except (IOError, OSError): self._body_position = object() if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.') if length: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: if files: (body, content_type) = self._encode_files(files, data) elif data: body = self._encode_params(data) if (isinstance(data, basestring) or hasattr(data, 'read')): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) if (content_type and ('content-type' not in self.headers)): self.headers['Content-Type'] = content_type self.body = body
'Prepare Content-Length header based on request method and body'
def prepare_content_length(self, body):
if (body is not None): length = super_len(body) if length: self.headers['Content-Length'] = builtin_str(length) elif ((self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None)): self.headers['Content-Length'] = '0'
'Prepares the given HTTP auth data.'
def prepare_auth(self, auth, url=''):
if (auth is None): url_auth = get_auth_from_url(self.url) auth = (url_auth if any(url_auth) else None) if auth: if (isinstance(auth, tuple) and (len(auth) == 2)): auth = HTTPBasicAuth(*auth) r = auth(self) self.__dict__.update(r.__dict__) self.prepare_content_length(self.body)
'Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib\'s design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand.'
def prepare_cookies(self, cookies):
if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if (cookie_header is not None): self.headers['Cookie'] = cookie_header
'Prepares the given hooks.'
def prepare_hooks(self, hooks):
hooks = (hooks or []) for event in hooks: self.register_hook(event, hooks[event])
'Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.'
def __bool__(self):
return self.ok
'Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.'
def __nonzero__(self):
return self.ok
'Allows you to use a response as an iterator.'
def __iter__(self):
return self.iter_content(128)
'Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.'
@property def ok(self):
try: self.raise_for_status() except HTTPError: return False return True
'True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`).'
@property def is_redirect(self):
return (('location' in self.headers) and (self.status_code in REDIRECT_STATI))
'True if this Response one of the permanent versions of redirect.'
@property def is_permanent_redirect(self):
return (('location' in self.headers) and (self.status_code in (codes.moved_permanently, codes.permanent_redirect)))
'Returns a PreparedRequest for the next request in a redirect chain, if there is one.'
@property def next(self):
return self._next
'The apparent encoding, provided by the chardet library.'
@property def apparent_encoding(self):
return chardet.detect(self.content)['encoding']
'Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response.'
def iter_content(self, chunk_size=1, decode_unicode=False):
def generate(): if hasattr(self.raw, 'stream'): try: for chunk in self.raw.stream(chunk_size, decode_content=True): (yield chunk) except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) else: while True: chunk = self.raw.read(chunk_size) if (not chunk): break (yield chunk) self._content_consumed = True if (self._content_consumed and isinstance(self._content, bool)): raise StreamConsumedError() elif ((chunk_size is not None) and (not isinstance(chunk_size, int))): raise TypeError(('chunk_size must be an int, it is instead a %s.' % type(chunk_size))) reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = (reused_chunks if self._content_consumed else stream_chunks) if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks
'Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe.'
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if (pending is not None): chunk = (pending + chunk) if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if (lines and lines[(-1)] and chunk and (lines[(-1)][(-1)] == chunk[(-1)])): pending = lines.pop() else: pending = None for line in lines: (yield line) if (pending is not None): (yield pending)
'Content of the response, in bytes.'
@property def content(self):
if (self._content is False): if self._content_consumed: raise RuntimeError('The content for this response was already consumed') if ((self.status_code == 0) or (self.raw is None)): self._content = None else: self._content = (bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()) self._content_consumed = True return self._content
'Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property.'
@property def text(self):
content = None encoding = self.encoding if (not self.content): return str('') if (self.encoding is None): encoding = self.apparent_encoding try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): content = str(self.content, errors='replace') return content
'Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json.'
def json(self, **kwargs):
if ((not self.encoding) and self.content and (len(self.content) > 3)): encoding = guess_json_utf(self.content) if (encoding is not None): try: return complexjson.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: pass return complexjson.loads(self.text, **kwargs)
'Returns the parsed header links of the response, if any.'
@property def links(self):
header = self.headers.get('link') l = {} if header: links = parse_header_links(header) for link in links: key = (link.get('rel') or link.get('url')) l[key] = link return l
'Raises stored :class:`HTTPError`, if one occurred.'
def raise_for_status(self):
http_error_msg = '' if isinstance(self.reason, bytes): try: reason = self.reason.decode('utf-8') except UnicodeDecodeError: reason = self.reason.decode('iso-8859-1') else: reason = self.reason if (400 <= self.status_code < 500): http_error_msg = (u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)) elif (500 <= self.status_code < 600): http_error_msg = (u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)) if http_error_msg: raise HTTPError(http_error_msg, response=self)
'Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.*'
def close(self):
if (not self._content_consumed): self.raw.close() release_conn = getattr(self.raw, 'release_conn', None) if (release_conn is not None): release_conn()
':rtype: str'
def build_digest_header(self, method, url):
realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] qop = self._thread_local.chal.get('qop') algorithm = self._thread_local.chal.get('algorithm') opaque = self._thread_local.chal.get('opaque') hash_utf8 = None if (algorithm is None): _algorithm = 'MD5' else: _algorithm = algorithm.upper() if ((_algorithm == 'MD5') or (_algorithm == 'MD5-SESS')): def md5_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.md5(x).hexdigest() hash_utf8 = md5_utf8 elif (_algorithm == 'SHA'): def sha_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha1(x).hexdigest() hash_utf8 = sha_utf8 KD = (lambda s, d: hash_utf8(('%s:%s' % (s, d)))) if (hash_utf8 is None): return None entdig = None p_parsed = urlparse(url) path = (p_parsed.path or '/') if p_parsed.query: path += ('?' + p_parsed.query) A1 = ('%s:%s:%s' % (self.username, realm, self.password)) A2 = ('%s:%s' % (method, path)) HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if (nonce == self._thread_local.last_nonce): self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 ncvalue = ('%08x' % self._thread_local.nonce_count) s = str(self._thread_local.nonce_count).encode('utf-8') s += nonce.encode('utf-8') s += time.ctime().encode('utf-8') s += os.urandom(8) cnonce = hashlib.sha1(s).hexdigest()[:16] if (_algorithm == 'MD5-SESS'): HA1 = hash_utf8(('%s:%s:%s' % (HA1, nonce, cnonce))) if (not qop): respdig = KD(HA1, ('%s:%s' % (nonce, HA2))) elif ((qop == 'auth') or ('auth' in qop.split(','))): noncebit = ('%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, 'auth', HA2)) respdig = KD(HA1, noncebit) else: return None self._thread_local.last_nonce = nonce base = ('username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (self.username, realm, nonce, path, respdig)) if opaque: base += (', opaque="%s"' % opaque) if algorithm: base += (', algorithm="%s"' % algorithm) if entdig: base += (', digest="%s"' % entdig) if qop: base += (', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)) return ('Digest %s' % base)
'Reset num_401_calls counter on redirects.'
def handle_redirect(self, r, **kwargs):
if r.is_redirect: self._thread_local.num_401_calls = 1
'Takes the given response and tries digest-auth, if needed. :rtype: requests.Response'
def handle_401(self, r, **kwargs):
if (not (400 <= r.status_code < 500)): self._thread_local.num_401_calls = 1 return r if (self._thread_local.pos is not None): r.request.body.seek(self._thread_local.pos) s_auth = r.headers.get('www-authenticate', '') if (('digest' in s_auth.lower()) and (self._thread_local.num_401_calls < 2)): self._thread_local.num_401_calls += 1 pat = re.compile('digest ', flags=re.IGNORECASE) self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1)) r.content r.close() prep = r.request.copy() extract_cookies_to_jar(prep._cookies, r.request, r.raw) prep.prepare_cookies(prep._cookies) prep.headers['Authorization'] = self.build_digest_header(prep.method, prep.url) _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r
'Receives a Response. Returns a redirect URI or ``None``'
def get_redirect_target(self, resp):
if resp.is_redirect: location = resp.headers['location'] if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
'Receives a Response. Returns a generator of Responses or Requests.'
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
hist = [] url = self.get_redirect_target(resp) while url: prepared_request = req.copy() hist.append(resp) resp.history = hist[1:] try: resp.content except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if (len(resp.history) >= self.max_redirects): raise TooManyRedirects(('Exceeded %s redirects.' % self.max_redirects), response=resp) resp.close() if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = ('%s:%s' % (to_native_string(parsed_rurl.scheme), url)) parsed = urlparse(url) url = parsed.geturl() if (not parsed.netloc): url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) if (resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect)): purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding') for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers try: del headers['Cookie'] except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) rewindable = ((prepared_request._body_position is not None) and (('Content-Length' in headers) or ('Transfer-Encoding' in headers))) if rewindable: rewind_body(prepared_request) req = prepared_request if yield_requests: (yield req) else: resp = self.send(req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) url = self.get_redirect_target(resp) (yield resp)
'When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.'
def rebuild_auth(self, prepared_request, response):
headers = prepared_request.headers url = prepared_request.url if ('Authorization' in headers): original_parsed = urlparse(response.request.url) redirect_parsed = urlparse(url) if (original_parsed.hostname != redirect_parsed.hostname): del headers['Authorization'] new_auth = (get_netrc_auth(url) if self.trust_env else None) if (new_auth is not None): prepared_request.prepare_auth(new_auth) return
'This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict'
def rebuild_proxies(self, prepared_request, proxies):
proxies = (proxies if (proxies is not None) else {}) headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if (self.trust_env and (not bypass_proxy)): environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if ('Proxy-Authorization' in headers): del headers['Proxy-Authorization'] try: (username, password) = get_auth_from_url(new_proxies[scheme]) except KeyError: (username, password) = (None, None) if (username and password): headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies
'When being redirected we may want to change the method of the request based on certain specs or browser behavior.'
def rebuild_method(self, prepared_request, response):
method = prepared_request.method if ((response.status_code == codes.see_other) and (method != 'HEAD')): method = 'GET' if ((response.status_code == codes.found) and (method != 'HEAD')): method = 'GET' if ((response.status_code == codes.moved) and (method == 'POST')): method = 'GET' prepared_request.method = method
'Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session\'s settings. :rtype: requests.PreparedRequest'
def prepare_request(self, request):
cookies = (request.cookies or {}) if (not isinstance(cookies, cookielib.CookieJar)): cookies = cookiejar_from_dict(cookies) merged_cookies = merge_cookies(merge_cookies(RequestsCookieJar(), self.cookies), cookies) auth = request.auth if (self.trust_env and (not auth) and (not self.auth)): auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare(method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks)) return p
'Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``\'filename\': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server\'s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, (\'cert\', \'key\') pair. :rtype: requests.Response'
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None):
req = Request(method=method.upper(), url=url, headers=headers, files=files, data=(data or {}), json=json, params=(params or {}), auth=auth, cookies=cookies, hooks=hooks) prep = self.prepare_request(req) proxies = (proxies or {}) settings = self.merge_environment_settings(prep.url, proxies, stream, verify, cert) send_kwargs = {'timeout': timeout, 'allow_redirects': allow_redirects} send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
'Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def get(self, url, **kwargs):
kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
'Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def options(self, url, **kwargs):
kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
'Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def head(self, url, **kwargs):
kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
'Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def post(self, url, data=None, json=None, **kwargs):
return self.request('POST', url, data=data, json=json, **kwargs)
'Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def put(self, url, data=None, **kwargs):
return self.request('PUT', url, data=data, **kwargs)
'Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def patch(self, url, data=None, **kwargs):
return self.request('PATCH', url, data=data, **kwargs)
'Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
def delete(self, url, **kwargs):
return self.request('DELETE', url, **kwargs)