desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Remove a line from the history buffer. Subclasses *must* provide an
implementation of this method.
:Parameters:
i : int
the 0-based index of the item to be removed'
| @abstract
def remove_item(self, i):
| pass
|
'Clear the history buffer. Subclasses *must* provide an
implementation of this method.'
| @abstract
def clear_history(self):
| pass
|
'Get a copy of the history buffer.
:rtype: list
:return: a list of commands from the history'
| def get_history_list(self):
| result = []
for i in range(1, (self.total + 1)):
result += [self.get_item(i)]
return result
|
'Remove all history items that match a regular expression.
:Parameters:
regexp_string : str
the uncompiled regular expression to match
:raise HistoryError: bad regular expression'
| def remove_matches(self, regexp_string):
| try:
pat = re.compile(regexp_string)
except:
raise HistoryError(str(sys.exc_info[1]))
buf = []
for i in range(1, (self.total + 1)):
s = self.get_item(i)
if (not pat.match(s)):
buf += [s]
self.replace_history(buf)
|
'Cut the history back to the specified index, removing all entries
more recent than that index.
:Parameters:
index : int
the index of the command that should become the last command
in the history
:raise IndexError: index out of range'
| def cut_back_to(self, index):
| if ((index > 0) and (index <= self.total)):
buf = []
for i in range(1, index):
buf += [self.get_item(i)]
self.replace_history(buf)
|
'Replace the entire contents of the history with another set of values
:Parameters:
commands : list
List of strings to put in the history after clearing it of any
existing entries'
| def replace_history(self, commands):
| self.clear_history()
for command in commands:
self.add_item(command, force=True)
|
'Save the history to a file. The file is overwritten with the contents
of the history buffer.
:Parameters:
path : str
Path to the history file to receive the output.
:raise IOError: Unable to open file'
| def save_history_file(self, path):
| log.debug(('Writing history file "%s"' % path))
with open(path, 'w') as f:
for i in range(1, (self.total + 1)):
f.write((self.get_item(i) + '\n'))
|
'Load the history buffer with the contents of a file, completely
replacing the in-memory history with the file\'s contents.
:Parameters:
path : str
Path to the history file to read
:raise IOError: Unable to open file'
| def load_history_file(self, path):
| log.debug(('Loading history file "%s"' % path))
with open(path, 'r') as f:
buf = []
for line in f:
buf += [line.strip()]
max = self.get_max_length()
if (len(buf) > max):
buf = buf[max]
self.replace_history(buf)
|
'Initialize an ``LRUDict`` that will hold, at most, ``max_capacity``
items. Attempts to insert more than ``max_capacity`` items in the
dictionary will cause the least-recently used entries to drop out of
the dictionary.
:Keywords:
max_capacity : int
The maximum size of the dictionary'
| def __init__(self, *args, **kw):
| if kw.has_key('max_capacity'):
self.__max_capacity = kw['max_capacity']
del kw['max_capacity']
else:
self.__max_capacity = sys.maxint
dict.__init__(self)
self.__removal_listeners = {}
self.__lru_queue = LRUList()
|
'Get the maximum capacity of the dictionary.
:rtype: int
:return: the maximum capacity'
| def get_max_capacity(self):
| return self.__max_capacity
|
'Set or change the maximum capacity of the dictionary. Reducing
the size of a dictionary with items already in it might result
in items being evicted.
:Parameters:
new_capacity : int
the new maximum capacity'
| def set_max_capacity(self, new_capacity):
| self.__max_capacity = new_capacity
if (len(self) > new_capacity):
self.__clear_to(new_capacity)
|
'Add an ejection listener to the dictionary. The listener function
should take at least two parameters: the key and value being removed.
It can also take additional parameters, which are passed through
unmodified.
An ejection listener is only notified when objects are ejected from
the cache to make room for new objects... | def add_ejection_listener(self, listener, *args):
| self.__removal_listeners[listener] = (True, args)
|
'Add a removal listener to the dictionary. The listener function should
take at least two parameters: the key and value being removed. It can
also take additional parameters, which are passed through unmodified.
A removal listener is notified when objects are ejected from the cache
to make room for new objects *and* wh... | def add_removal_listener(self, listener, *args):
| self.__removal_listeners[listener] = (False, args)
|
'Remove the specified removal or ejection listener from the list of
listeners.
:Parameters:
listener : function
Function object to remove
:rtype: bool
:return: ``True`` if the listener was found and removed; ``False``
otherwise'
| def remove_listener(self, listener):
| try:
del self.__removal_listeners[listener]
return True
except KeyError:
return False
|
'Clear all removal and ejection listeners from the list of listeners.'
| def clear_listeners(self):
| for key in self.__removal_listeners.keys():
del self.__removal_listeners[key]
|
'Pops the least recently used recent key/value pair from the
dictionary.
:rtype: tuple
:return: the least recent key/value pair, as a tuple
:raise KeyError: empty dictionary'
| def popitem(self):
| if (len(self) == 0):
raise KeyError, 'Attempted popitem() on empty dictionary'
lru_entry = self.__lru_queue.remove_tail()
dict.__delitem__(self, lru_entry.key)
return (lru_entry.key, lru_entry.value)
|
'Create a new ``Includer`` object.
:Parameters:
source : file or str
The source to be read and expanded. May be an open file-like
object, a path name, or a URL string.
include_regex : str
Regular expression defining the include syntax. Must contain a
single parenthetical group that can be used to extract the
included f... | def __init__(self, source, include_regex='^%include\\s"([^"]+)"', max_nest_level=100, output=None):
| if isinstance(source, str):
(f, is_url, name) = self.__open(source, None, False)
else:
f = source
is_url = False
try:
name = source.name
except AttributeError:
name = None
self.closed = False
self.mode = None
self.__include_pattern = re... |
'Get the name of the file being processed.'
| @property
def name(self):
| return self.__name
|
'A file object is its own iterator.
:rtype: string
:return: the next line from the file
:raise StopIteration: end of file
:raise IncludeError: on error'
| def next(self):
| line = self.readline()
if ((line == None) or (len(line) == 0)):
raise StopIteration
return line
|
'Close the includer, preventing any further I/O operations.'
| def close(self):
| if (not self.closed):
self.closed = true
self.__f.close()
del self.__f
|
'Get the file descriptor. Returns the descriptor of the file being
read.
:rtype: int
:return: the file descriptor of the file being read'
| def fileno(self):
| _complain_if_closed(self.closed)
return self.__f.fileno()
|
'Determine whether the file being processed is a TTY or not.
:return: ``True`` or ``False``'
| def isatty(self):
| _complain_if_closed(self.closed)
return self.__f.isatty()
|
'Seek to the specified file offset in the include-processed file.
:Parameters:
pos : int
file offset
mode : int
the seek mode, as specified to a Python file\'s ``seek()``
method'
| def seek(self, pos, mode=0):
| self.__f.seek(pos, mode)
|
'Get the current file offset.
:rtype: int
:return: current file offset'
| def tell(self):
| _complain_if_closed(self.closed)
return self.__f.tell()
|
'Read *n* bytes from the open file.
:Parameters:
n : int
Number of bytes to read. A negative number instructs
the method to read all remaining bytes.
:return: the bytes read'
| def read(self, n=(-1)):
| _complain_if_closed(self.closed)
return self.__f.read(n)
|
'Read the next line from the file.
:Parameters:
length : int
a length hint, or negative if you don\'t care
:rtype: str
:return: the line read'
| def readline(self, length=(-1)):
| _complain_if_closed(self.closed)
return self.__f.readline(length)
|
'Read all remaining lines in the file.
:rtype: array
:return: array of lines'
| def readlines(self, sizehint=0):
| _complain_if_closed(self.closed)
return self.__f.readlines(sizehint)
|
'Not supported, since ``Includer`` objects are read-only.'
| def truncate(self, size=None):
| raise IncludeError, 'Includers are read-only file objects.'
|
'Not supported, since ``Includer`` objects are read-only.'
| def write(self, s):
| raise IncludeError, 'Includers are read-only file objects.'
|
'Not supported, since ``Includer`` objects are read-only.'
| def writelines(self, iterable):
| raise IncludeError, 'Includers are read-only file objects.'
|
'No-op.'
| def flush(self):
| pass
|
'Retrieve the entire contents of the file, which includes expanded,
at any time before the ``close()`` method is called.
:rtype: string
:return: a single string containing the contents of the file'
| def getvalue(self):
| return ''.join(self.readlines())
|
'Returns true if this range can be satisfied by the resource
with the given byte length.'
| def satisfiable(self, length):
| return (self.range_for_length(length) is not None)
|
'*If* there is only one range, and *if* it is satisfiable by
the given length, then return a (begin, end) non-inclusive range
of bytes to serve. Otherwise return None'
| def range_for_length(self, length):
| if ((length is None) or (len(self.ranges) != 1)):
return None
(start, end) = self.ranges[0]
if (end is None):
end = length
if (start < 0):
start += length
if _is_content_range_valid(start, end, length):
stop = min(end, length)
return (start, stop)
... |
'Works like range_for_length; returns None or a ContentRange object
You can use it like::
response.content_range = req.range.content_range(response.content_length)
Though it\'s still up to you to actually serve that content range!'
| def content_range(self, length):
| range = self.range_for_length(length)
if (range is None):
return None
return ContentRange(range[0], range[1], length)
|
'Parse the header; may return None if header is invalid'
| @classmethod
def parse(cls, header):
| bytes = cls.parse_bytes(header)
if (bytes is None):
return None
(units, ranges) = bytes
if ((units != 'bytes') or (ranges is None)):
return None
return cls(ranges)
|
'Parse a Range header into (bytes, list_of_ranges).
ranges in list_of_ranges are non-inclusive (unlike the HTTP header).
Will return None if the header is invalid'
| @staticmethod
def parse_bytes(header):
| if (not header):
raise TypeError('The header must not be empty')
ranges = []
last_end = 0
try:
(units, range) = header.split('=', 1)
units = units.strip().lower()
for item in range.split(','):
if ('-' not in item):
raise ValueErr... |
'Mostly so you can unpack this, like:
start, stop, length = res.content_range'
| def __iter__(self):
| return iter([self.start, self.stop, self.length])
|
'Parse the header. May return None if it cannot parse.'
| @classmethod
def parse(cls, value):
| if (value is None):
return None
value = value.strip()
if (not value.startswith('bytes ')):
return None
value = value[len('bytes '):].strip()
if ('/' not in value):
return None
(range, length) = value.split('/', 1)
if (length == '*'):
length = None
el... |
'Reads a response from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the response, not the end of the
file.
This reads the response as represented by ``str(resp)``; it
may not read every valid HTTP response properly. Responses
must have a ``Content-Length``'
| @classmethod
def from_file(cls, fp):
| headerlist = []
status = fp.readline().strip()
while 1:
line = fp.readline().strip()
if (not line):
break
try:
(header_name, value) = line.split(':', 1)
except ValueError:
raise ValueError(('Bad header line: %r' % line))
he... |
'Makes a copy of the response'
| def copy(self):
| app_iter = list(self._app_iter)
iter_close(self._app_iter)
self._app_iter = list(app_iter)
return self.__class__(content_type=False, status=self._status, headerlist=self._headerlist[:], app_iter=app_iter, conditional_response=self.conditional_response)
|
'The status string'
| def _status__get(self):
| return self._status
|
'The status as an integer'
| def _status_int__get(self):
| return int(self._status.split()[0])
|
'The list of response headers'
| def _headerlist__get(self):
| return self._headerlist
|
'The headers in a dictionary-like object'
| def _headers__get(self):
| if (self._headers is None):
self._headers = ResponseHeaders.view_list(self.headerlist)
return self._headers
|
'The body of the response, as a ``str``. This will read in the
entire app_iter if necessary.'
| def _body__get(self):
| app_iter = self._app_iter
if (isinstance(app_iter, list) and (len(app_iter) == 1)):
return app_iter[0]
if (app_iter is None):
raise AttributeError('No body has been set')
try:
body = ''.join(app_iter)
finally:
iter_close(app_iter)
if isinstance(body, u... |
'Get/set the unicode value of the body (using the charset of the
Content-Type)'
| def _text__get(self):
| if (not self.charset):
raise AttributeError('You cannot access Response.text unless charset is set')
body = self.body
return body.decode(self.charset, self.unicode_errors)
|
'A file-like object that can be used to write to the
body. If you passed in a list app_iter, that app_iter will be
modified by writes.'
| def _body_file__get(self):
| return ResponseBodyFile(self)
|
'Returns the app_iter of the response.
If body was set, this will create an app_iter from that body
(a single-item list)'
| def _app_iter__get(self):
| return self._app_iter
|
'Get/set the charset (in the Content-Type)'
| def _charset__get(self):
| header = self.headers.get('Content-Type')
if (not header):
return None
match = CHARSET_RE.search(header)
if match:
return match.group(1)
return None
|
'Get/set the Content-Type header (or None), *without* the
charset or any parameters.
If you include parameters (or ``;`` at all) when setting the
content_type, any existing parameters will be deleted;
otherwise they will be preserved.'
| def _content_type__get(self):
| header = self.headers.get('Content-Type')
if (not header):
return None
return header.split(';', 1)[0]
|
'A dictionary of all the parameters in the content type.
(This is not a view, set to change, modifications of the dict would not be
applied otherwise)'
| def _content_type_params__get(self):
| params = self.headers.get('Content-Type', '')
if (';' not in params):
return {}
params = params.split(';', 1)[1]
result = {}
for match in _PARAM_RE.finditer(params):
result[match.group(1)] = (match.group(2) or match.group(3) or '')
return result
|
'Set (add) a cookie for the response'
| def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=False, httponly=False, comment=None, expires=None, overwrite=False):
| if overwrite:
self.unset_cookie(key, strict=False)
if (value is None):
value = ''
max_age = 0
expires = timedelta(days=(-5))
elif ((expires is None) and (max_age is not None)):
if isinstance(max_age, int):
max_age = timedelta(seconds=max_age)
expir... |
'Delete a cookie from the client. Note that path and domain must match
how the cookie was originally set.
This sets the cookie to the empty string, and max_age=0 so
that it should expire immediately.'
| def delete_cookie(self, key, path='/', domain=None):
| self.set_cookie(key, None, path=path, domain=domain)
|
'Unset a cookie with the given name (remove it from the
response).'
| def unset_cookie(self, key, strict=True):
| existing = self.headers.getall('Set-Cookie')
if ((not existing) and (not strict)):
return
cookies = Cookie()
for header in existing:
cookies.load(header)
if (key in cookies):
del cookies[key]
del self.headers['Set-Cookie']
for m in cookies.values():
... |
'Merge the cookies that were set on this response with the
given `resp` object (which can be any WSGI application).
If the `resp` is a :class:`webob.Response` object, then the
other object will be modified in-place.'
| def merge_cookies(self, resp):
| if (not self.headers.get('Set-Cookie')):
return resp
if isinstance(resp, Response):
for header in self.headers.getall('Set-Cookie'):
resp.headers.add('Set-Cookie', header)
return resp
else:
c_headers = [h for h in self.headerlist if (h[0].lower() == 'set-cookie')]... |
'Get/set/modify the Cache-Control header (`HTTP spec section 14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)'
| def _cache_control__get(self):
| value = self.headers.get('cache-control', '')
if (self._cache_control_obj is None):
self._cache_control_obj = CacheControl.parse(value, updates_to=self._update_cache_control, type='response')
self._cache_control_obj.header_value = value
if (self._cache_control_obj.header_value != value):
... |
'Set expiration on this request. This sets the response to
expire in the given seconds, and any other attributes are used
for cache_control (e.g., private=True, etc).'
| def _cache_expires(self, seconds=0, **kw):
| if (seconds is True):
seconds = 0
elif isinstance(seconds, timedelta):
seconds = timedelta_to_seconds(seconds)
cache_control = self.cache_control
if (seconds is None):
pass
elif (not seconds):
cache_control.no_store = True
cache_control.no_cache = True
... |
'Encode the content with the given encoding (only gzip and
identity are supported).'
| def encode_content(self, encoding='gzip', lazy=False):
| assert (encoding in ('identity', 'gzip')), ('Unknown encoding: %r' % encoding)
if (encoding == 'identity'):
self.decode_content()
return
if (self.content_encoding == 'gzip'):
return
if lazy:
self.app_iter = gzip_app_iter(self._app_iter)
self.content_length =... |
'Generate an etag for the response object using an MD5 hash of
the body (the body parameter, or ``self.body`` if not given)
Sets ``self.etag``
If ``set_content_md5`` is True sets ``self.content_md5`` as well'
| def md5_etag(self, body=None, set_content_md5=False):
| if (body is None):
body = self.body
try:
from hashlib import md5
except ImportError:
from md5 import md5
md5_digest = md5(body).digest().encode('base64').replace('\n', '')
self.etag = md5_digest.strip('=')
if set_content_md5:
self.content_md5 = md5_digest
|
'Return the request associated with this response if any.'
| def _request__get(self):
| _warn_req()
if ((self._request is None) and (self._environ is not None)):
self._request = self.RequestClass(self._environ)
return self._request
|
'Get/set the request environ associated with this response, if
any.'
| def _environ__get(self):
| _warn_req()
return self._environ
|
'WSGI application interface'
| def __call__(self, environ, start_response):
| if self.conditional_response:
return self.conditional_response_app(environ, start_response)
headerlist = self._abs_headerlist(environ)
start_response(self.status, headerlist)
if (environ['REQUEST_METHOD'] == 'HEAD'):
return EmptyResponse(self._app_iter)
return self._app_iter
|
'Returns a headerlist, with the Location header possibly
made absolute given the request environ.'
| def _abs_headerlist(self, environ):
| headerlist = self.headerlist
for (name, value) in headerlist:
if (name.lower() == 'location'):
if SCHEME_RE.search(value):
break
new_location = urlparse.urljoin(_request_uri(environ), value)
headerlist = list(headerlist)
idx = headerlist.in... |
'Like the normal __call__ interface, but checks conditional headers:
* If-Modified-Since (304 Not Modified; only on GET, HEAD)
* If-None-Match (304 Not Modified; only on GET, HEAD)
* Range (406 Partial Content; only on GET, HEAD)'
| def conditional_response_app(self, environ, start_response):
| req = self.RequestClass(environ)
status304 = False
headerlist = self._abs_headerlist(environ)
if (req.method in self._safe_methods):
if (req.if_none_match and self.etag):
status304 = (self.etag in req.if_none_match)
elif (req.if_modified_since and self.last_modified):
... |
'Return a new app_iter built from the response app_iter, that
serves up only the given ``start:stop`` range.'
| def app_iter_range(self, start, stop):
| app_iter = self._app_iter
if hasattr(app_iter, 'app_iter_range'):
return app_iter.app_iter_range(start, stop)
return AppIterRange(app_iter, start, stop)
|
'Create a dict that is a view on the given list'
| @classmethod
def view_list(cls, lst):
| if (not isinstance(lst, list)):
raise TypeError(('%s.view_list(obj) takes only actual list objects, not %r' % (cls.__name__, lst)))
obj = cls()
obj._items = lst
return obj
|
'Create a dict from a cgi.FieldStorage instance'
| @classmethod
def from_fieldstorage(cls, fs):
| obj = cls()
for field in (fs.list or ()):
if field.filename:
obj.add(field.name, field)
else:
obj.add(field.name, field.value)
return obj
|
'Add the key and value, not overwriting any previous value.'
| def add(self, key, value):
| self._items.append((key, value))
|
'Return a list of all values matching the key (may be an empty list)'
| def getall(self, key):
| result = []
for (k, v) in self._items:
if (key == k):
result.append(v)
return result
|
'Get one value matching the key, raising a KeyError if multiple
values were found.'
| def getone(self, key):
| v = self.getall(key)
if (not v):
raise KeyError(('Key not found: %r' % key))
if (len(v) > 1):
raise KeyError(('Multiple values match %r: %r' % (key, v)))
return v[0]
|
'Returns a dictionary where the values are either single
values, or a list of values when a key/value appears more than
once in this dictionary. This is similar to the kind of
dictionary often used to represent the variables in a web
request.'
| def mixed(self):
| result = {}
multi = {}
for (key, value) in self.iteritems():
if (key in result):
if (key in multi):
result[key].append(value)
else:
result[key] = [result[key], value]
multi[key] = None
else:
result[key] = val... |
'Returns a dictionary where each key is associated with a list of values.'
| def dict_of_lists(self):
| r = {}
for (key, val) in self.iteritems():
r.setdefault(key, []).append(val)
return r
|
'Decode the specified value to unicode. Assumes value is a ``str`` or
`FieldStorage`` object.
``FieldStorage`` objects are specially handled.'
| def _decode_value(self, value):
| if isinstance(value, cgi.FieldStorage):
value = copy.copy(value)
if self.decode_keys:
if (not isinstance(value.name, unicode)):
value.name = value.name.decode(self.encoding, self.errors)
if value.filename:
if (not isinstance(value.filename, unicode)):
... |
'Add the key and value, not overwriting any previous value.'
| def add(self, key, value):
| self.multi.add(self._encode_key(key), self._encode_value(value))
|
'Return a list of all values matching the key (may be an empty list)'
| def getall(self, key):
| return map(self._decode_value, self.multi.getall(self._encode_key(key)))
|
'Get one value matching the key, raising a KeyError if multiple
values were found.'
| def getone(self, key):
| return self._decode_value(self.multi.getone(self._encode_key(key)))
|
'Returns a dictionary where the values are either single
values, or a list of values when a key/value appears more than
once in this dictionary. This is similar to the kind of
dictionary often used to represent the variables in a web
request.'
| def mixed(self):
| unicode_mixed = {}
for (key, value) in self.multi.mixed().iteritems():
if isinstance(value, list):
value = [self._decode_value(value) for value in value]
else:
value = self._decode_value(value)
unicode_mixed[self._decode_key(key)] = value
return unicode_mixed
|
'Returns a dictionary where each key is associated with a
list of values.'
| def dict_of_lists(self):
| unicode_dict = {}
for (key, value) in self.multi.dict_of_lists().iteritems():
value = [self._decode_value(value) for value in value]
unicode_dict[self._decode_key(key)] = value
return unicode_dict
|
'Assign to new_dict.updated to track updates'
| def _updated(self):
| updated = self.updated
if (updated is not None):
args = self.updated_args
if (args is None):
args = (self,)
updated(*args)
|
'Parse the header, returning a CacheControl object.
The object is bound to the request or response object
``updates_to``, if that is given.'
| @classmethod
def parse(cls, header, updates_to=None, type=None):
| if updates_to:
props = cls.update_dict()
props.updated = updates_to
else:
props = {}
for match in token_re.finditer(header):
name = match.group(1)
value = (match.group(2) or match.group(3) or None)
if value:
try:
value = int(value)
... |
'Returns a copy of this object.'
| def copy(self):
| return self.__class__(self.properties.copy(), type=self.type)
|
'Parse this from a header value'
| @classmethod
def parse(cls, value):
| results = []
weak_results = []
while value:
if value.lower().startswith('w/'):
weak = True
value = value[2:]
else:
weak = False
if value.startswith('"'):
try:
(etag, rest) = value[1:].split('"', 1)
except Val... |
'Return True if the If-Range header matches the given etag or last_modified'
| def match(self, etag=None, last_modified=None):
| if (self.date is not None):
if (last_modified is None):
return False
return (last_modified <= self.date)
elif (self.etag is not None):
if (not etag):
return False
return (etag in self.etag)
return True
|
'Return True if this matches the given ``webob.Response`` instance.'
| def match_response(self, response):
| return self.match(etag=response.etag, last_modified=response.last_modified)
|
'Parse this from a header value.'
| @classmethod
def parse(cls, value):
| date = etag = None
if (not value):
etag = NoETag()
elif (value and value.endswith(' GMT')):
date = parse_date(value)
else:
etag = ETagMatcher.parse(value)
return cls(etag=etag, date=date)
|
'Parse ``Accept-*`` style header.
Return iterator of ``(value, quality)`` pairs.
``quality`` defaults to 1.'
| @staticmethod
def parse(value):
| for match in part_re.finditer((',' + value)):
name = match.group(1)
if (name == 'q'):
continue
quality = (match.group(2) or '')
if quality:
try:
quality = max(min(float(quality), 1), 0)
(yield (name, quality))
co... |
'Returns true if the given object is listed in the accepted
types.'
| def __contains__(self, offer):
| for (mask, quality) in self._parsed_nonzero:
if self._match(mask, offer):
return True
|
'Return the quality of the given offer. Returns None if there
is no match (not 0).'
| def quality(self, offer, modifier=1):
| bestq = 0
for (mask, q) in self._parsed:
if self._match(mask, offer):
bestq = max(bestq, (q * modifier))
return (bestq or None)
|
'DEPRECATED
Returns the first allowed offered type. Ignores quality.
Returns the first offered type if nothing else matches; or if you include None
at the end of the match list then that will be returned.'
| def first_match(self, offers):
| _warn_first_match()
if (not offers):
raise ValueError('You must pass in a non-empty list')
for offer in offers:
if (offer is None):
return None
for (mask, quality) in self._parsed_nonzero:
if self._match(mask, offer):
return o... |
'Returns the best match in the sequence of offered types.
The sequence can be a simple sequence, or you can have
``(match, server_quality)`` items in the sequence. If you
have these tuples then the client quality is multiplied by the
server_quality to get a total. If two matches have equal
weight, then the one that s... | def best_match(self, offers, default_match=None):
| best_quality = (-1)
best_offer = default_match
matched_by = '*/*'
for offer in offers:
if isinstance(offer, (tuple, list)):
(offer, server_quality) = offer
else:
server_quality = 1
for (mask, quality) in self._parsed_nonzero:
possible_quality =... |
'Return all the matches in order of quality, with fallback (if
given) at the end.'
| def best_matches(self, fallback=None):
| items = [i for (i, q) in sorted(self._parsed, key=(lambda iq: (- iq[1])))]
if fallback:
for (index, item) in enumerate(items):
if self._match(item, fallback):
items[index:] = [fallback]
break
else:
items.append(fallback)
return items
|
'Returns true if any HTML-like type is accepted'
| def accept_html(self):
| return (('text/html' in self) or ('application/xhtml+xml' in self) or ('application/xml' in self) or ('text/xml' in self))
|
'Check if the offer is covered by the mask'
| def _match(self, mask, offer):
| _check_offer(offer)
if ('*' not in mask):
return (offer == mask)
elif (mask == '*/*'):
return True
else:
assert mask.endswith('/*')
mask_major = mask[:(-2)]
offer_major = offer.split('/', 1)[0]
return (offer_major == mask_major)
|
'Call this as a WSGI application or with a request'
| def __call__(self, req, *args, **kw):
| func = self.func
if (func is None):
if (args or kw):
raise TypeError(('Unbound %s can only be called with the function it will wrap' % self.__class__.__name__))
func = req
return self.clone(func)
if isinstance(req, dict):
if ((len(... |
'Run a GET request on this application, returning a Response.
This creates a request object using the given URL, and any
other keyword arguments are set on the request object (e.g.,
``last_modified=datetime.now()``).
resp = myapp.get(\'/article?id=10\')'
| def get(self, url, **kw):
| kw.setdefault('method', 'GET')
req = self.RequestClass.blank(url, **kw)
return self(req)
|
'Run a POST request on this application, returning a Response.
The second argument (`POST`) can be the request body (a
string), or a dictionary or list of two-tuples, that give the
POST body.
resp = myapp.post(\'/article/new\',
dict(title=\'My Day\',
content=\'I ate a sandwich\'))'
| def post(self, url, POST=None, **kw):
| kw.setdefault('method', 'POST')
req = self.RequestClass.blank(url, POST=POST, **kw)
return self(req)
|
'Run a request on this application, returning a Response.
This can be used for DELETE, PUT, etc requests. E.g.::
resp = myapp.request(\'/article/1\', method=\'PUT\', body=\'New article\')'
| def request(self, url, **kw):
| req = self.RequestClass.blank(url, **kw)
return self(req)
|
'Call the wrapped function; override this in a subclass to
change how the function is called.'
| def call_func(self, req, *args, **kwargs):
| return self.func(req, *args, **kwargs)
|
'Creates a copy/clone of this object, but with some
parameters rebound'
| def clone(self, func=None, **kw):
| kwargs = {}
if (func is not None):
kwargs['func'] = func
if (self.RequestClass is not self.__class__.RequestClass):
kwargs['RequestClass'] = self.RequestClass
if self.args:
kwargs['args'] = self.args
if self.kwargs:
kwargs['kwargs'] = self.kwargs
kwargs.update(kw)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.