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 whet... | 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 optiona... | 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(**progre... |
'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['ax... |
'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']... |
'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\... | 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=(lam... |
'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] *... |
'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'])
s... |
'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 rati... |
'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 = Ra... |
'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.set... |
'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 coo... | 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 CookieConf... | 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 ar... |
'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]
... |
'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-tup... | @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 ... |
'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 isins... |
'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) =... |
'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, (ba... |
'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_... |
'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 <PreparedReq... | 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 ... | 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:
... |
'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... |
'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().jo... |
'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 s... | @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, er... |
'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
... |
'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... |
'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'
... |
'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_40... |
'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=... |
'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_... |
'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-Auth... | 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... |
'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 = 'GE... |
'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.... | 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)):
... |
'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:`Re... | 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, verif... |
'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 ... | 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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.