desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Time, in 12-hour hours and minutes, with minutes left off if they\'re zero. Examples: \'1\', \'1:30\', \'2:05\', \'2\' Proprietary extension.'
def f(self):
if (self.data.minute == 0): return self.g() return (u'%s:%s' % (self.g(), self.i()))
'Hour, 12-hour format without leading zeros; i.e. \'1\' to \'12\''
def g(self):
if (self.data.hour == 0): return 12 if (self.data.hour > 12): return (self.data.hour - 12) return self.data.hour
'Hour, 24-hour format without leading zeros; i.e. \'0\' to \'23\''
def G(self):
return self.data.hour
'Hour, 12-hour format; i.e. \'01\' to \'12\''
def h(self):
return (u'%02d' % self.g())
'Hour, 24-hour format; i.e. \'00\' to \'23\''
def H(self):
return (u'%02d' % self.G())
'Minutes; i.e. \'00\' to \'59\''
def i(self):
return (u'%02d' % self.data.minute)
'Time, in 12-hour hours, minutes and \'a.m.\'/\'p.m.\', with minutes left off if they\'re zero and the strings \'midnight\' and \'noon\' if appropriate. Examples: \'1 a.m.\', \'1:30 p.m.\', \'midnight\', \'noon\', \'12:30 p.m.\' Proprietary extension.'
def P(self):
if ((self.data.minute == 0) and (self.data.hour == 0)): return _(u'midnight') if ((self.data.minute == 0) and (self.data.hour == 12)): return _(u'noon') return (u'%s %s' % (self.f(), self.a()))
'Seconds; i.e. \'00\' to \'59\''
def s(self):
return (u'%02d' % self.data.second)
'Microseconds; i.e. \'000000\' to \'999999\''
def u(self):
return (u'%06d' % self.data.microsecond)
'Month, textual, 3 letters, lowercase; e.g. \'jan\''
def b(self):
return MONTHS_3[self.data.month]
'ISO 8601 Format Example : \'2008-01-02T10:30:00.000123\''
def c(self):
return self.data.isoformat()
'Day of the month, 2 digits with leading zeros; i.e. \'01\' to \'31\''
def d(self):
return (u'%02d' % self.data.day)
'Day of the week, textual, 3 letters; e.g. \'Fri\''
def D(self):
return WEEKDAYS_ABBR[self.data.weekday()]
'Timezone name if available'
def e(self):
try: if (hasattr(self.data, u'tzinfo') and self.data.tzinfo): return (self.data.tzinfo.tzname(self.data) or u'') except NotImplementedError: pass return u''
'Alternative month names as required by some locales. Proprietary extension.'
def E(self):
return MONTHS_ALT[self.data.month]
'Month, textual, long; e.g. \'January\''
def F(self):
return MONTHS[self.data.month]
'\'1\' if Daylight Savings Time, \'0\' otherwise.'
def I(self):
if (self.timezone and self.timezone.dst(self.data)): return u'1' else: return u'0'
'Day of the month without leading zeros; i.e. \'1\' to \'31\''
def j(self):
return self.data.day
'Day of the week, textual, long; e.g. \'Friday\''
def l(self):
return WEEKDAYS[self.data.weekday()]
'Boolean for whether it is a leap year; i.e. True or False'
def L(self):
return calendar.isleap(self.data.year)
'Month; i.e. \'01\' to \'12\''
def m(self):
return (u'%02d' % self.data.month)
'Month, textual, 3 letters; e.g. \'Jan\''
def M(self):
return MONTHS_3[self.data.month].title()
'Month without leading zeros; i.e. \'1\' to \'12\''
def n(self):
return self.data.month
'Month abbreviation in Associated Press style. Proprietary extension.'
def N(self):
return MONTHS_AP[self.data.month]
'ISO 8601 year number matching the ISO week number (W)'
def o(self):
return self.data.isocalendar()[0]
'Difference to Greenwich time in hours; e.g. \'+0200\', \'-0430\''
def O(self):
seconds = self.Z() sign = (u'-' if (seconds < 0) else u'+') seconds = abs(seconds) return (u'%s%02d%02d' % (sign, (seconds // 3600), ((seconds // 60) % 60)))
'RFC 2822 formatted date; e.g. \'Thu, 21 Dec 2000 16:01:07 +0200\''
def r(self):
return self.format(u'D, j M Y H:i:s O')
'English ordinal suffix for the day of the month, 2 characters; i.e. \'st\', \'nd\', \'rd\' or \'th\''
def S(self):
if (self.data.day in (11, 12, 13)): return u'th' last = (self.data.day % 10) if (last == 1): return u'st' if (last == 2): return u'nd' if (last == 3): return u'rd' return u'th'
'Number of days in the given month; i.e. \'28\' to \'31\''
def t(self):
return (u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1])
'Time zone of this machine; e.g. \'EST\' or \'MDT\''
def T(self):
name = ((self.timezone and self.timezone.tzname(self.data)) or None) if (name is None): name = self.format(u'O') return six.text_type(name)
'Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)'
def U(self):
if (isinstance(self.data, datetime.datetime) and is_aware(self.data)): return int(calendar.timegm(self.data.utctimetuple())) else: return int(time.mktime(self.data.timetuple()))
'Day of the week, numeric, i.e. \'0\' (Sunday) to \'6\' (Saturday)'
def w(self):
return ((self.data.weekday() + 1) % 7)
'ISO-8601 week number of year, weeks starting on Monday'
def W(self):
week_number = None jan1_weekday = (self.data.replace(month=1, day=1).weekday() + 1) weekday = (self.data.weekday() + 1) day_of_year = self.z() if ((day_of_year <= (8 - jan1_weekday)) and (jan1_weekday > 4)): if ((jan1_weekday == 5) or ((jan1_weekday == 6) and calendar.isleap((self.data.year - 1)))): week_number = 53 else: week_number = 52 else: if calendar.isleap(self.data.year): i = 366 else: i = 365 if ((i - day_of_year) < (4 - weekday)): week_number = 1 else: j = ((day_of_year + (7 - weekday)) + (jan1_weekday - 1)) week_number = (j // 7) if (jan1_weekday > 4): week_number -= 1 return week_number
'Year, 2 digits; e.g. \'99\''
def y(self):
return six.text_type(self.data.year)[2:]
'Year, 4 digits; e.g. \'1999\''
def Y(self):
return self.data.year
'Day of the year; i.e. \'0\' to \'365\''
def z(self):
doy = (self.year_days[self.data.month] + self.data.day) if (self.L() and (self.data.month > 2)): doy += 1 return doy
'Time zone offset in seconds (i.e. \'-43200\' to \'43200\'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'
def Z(self):
if (not self.timezone): return 0 offset = self.timezone.utcoffset(self.data) return ((offset.days * 86400) + offset.seconds)
'Get information about any POST forms in the template. Returns [(linenumber, csrf_token added)]'
def post_form_info(self):
forms = {} form_line = 0 for (ln, line) in enumerate(self.content.split('\n')): if ((not form_line) and _POST_FORM_RE.search(line)): form_line = (ln + 1) forms[form_line] = False if (form_line and _TOKEN_RE.search(line)): forms[form_line] = True form_line = 0 if (form_line and _FORM_CLOSE_RE.search(line)): form_line = 0 return forms.items()
'Returns true if this template includes template \'t\' (via {% include %})'
def includes_template(self, t):
for r in t.relative_filenames: if re.search((('\\{%\\s*include\\s+(\\\'|")' + re.escape(r)) + '(\\1)\\s*%\\}'), self.content): return True return False
'Returns all templates that include this one, recursively. (starting with this one)'
def related_templates(self):
try: return self._related_templates except AttributeError: pass retval = set([self]) for t in self.all_templates: if t.includes_template(self): retval = retval.union(t.related_templates()) self._related_templates = retval return retval
'Convert a representation node to a Python object.'
def from_yaml(cls, loader, node):
return loader.construct_yaml_object(node, cls)
'Convert a Python object to a representation node.'
def to_yaml(cls, dumper, data):
return dumper.represent_yaml_object(cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style)
'Initialize the scanner.'
def __init__(self):
self.done = False self.flow_level = 0 self.tokens = [] self.fetch_stream_start() self.tokens_taken = 0 self.indent = (-1) self.indents = [] self.allow_simple_key = True self.possible_simple_keys = {}
'*If* there is only one range, and *if* it is satisfiable by the given length, then return a (start, end) non-inclusive range of bytes to serve. Otherwise return None'
def range_for_length(self, length):
if (length is None): return None (start, end) = (self.start, self.end) 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) else: return None
'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):
m = _rx_range.match((header or '')) if (not m): return None (start, end) = m.groups() if (not start): return cls((- int(end)), None) start = int(start) if (not end): return cls(start, None) end = (int(end) + 1) if (start >= end): return None return cls(start, end)
'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):
m = _rx_content_range.match((value or '')) if (not m): return None (s, e, l) = m.groups() if s: s = int(s) e = (int(e) + 1) l = (l and int(l)) if (not _is_content_range_valid(s, e, l, response=True)): return None return cls(s, e, l)
'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() is_text = isinstance(status, text_type) if is_text: _colon = ':' else: _colon = ':' while 1: line = fp.readline().strip() if (not line): break try: (header_name, value) = line.split(_colon, 1) except ValueError: raise ValueError(('Bad header line: %r' % line)) value = value.strip() if (not is_text): header_name = header_name.decode('utf-8') value = value.decode('utf-8') headerlist.append((header_name, value)) r = cls(status=status, headerlist=headerlist, app_iter=()) body = fp.read((r.content_length or 0)) if is_text: r.text = body else: r.body = body return r
'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_code__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, text_type): raise _error_unicode_in_app_iter(app_iter, body) self._app_iter = [body] if (len(body) == 0): pass elif (self.content_length is None): self.content_length = len(body) elif (self.content_length != len(body)): raise AssertionError(('Content-Length is different from actual app_iter length (%r!=%r)' % (self.content_length, len(body)))) return body
'Access the body of the response as JSON'
def _json_body__get(self):
return json.loads(self.body.decode((self.charset or 'UTF-8')))
'Get/set the text 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. Arguments are: ``key`` The cookie name. ``value`` The cookie value, which should be a string or ``None``. If ``value`` is ``None``, it\'s equivalent to calling the :meth:`webob.response.Response.unset_cookie` method for this cookie key (it effectively deletes the cookie on the client). ``max_age`` An integer representing a number of seconds or ``None``. If this value is an integer, it is used as the ``Max-Age`` of the generated cookie. If ``expires`` is not passed and this value is an integer, the ``max_age`` value will also influence the ``Expires`` value of the cookie (``Expires`` will be set to now + max_age). If this value is ``None``, the cookie will not have a ``Max-Age`` value (unless ``expires`` is also sent). ``path`` A string representing the cookie ``Path`` value. It defaults to ``domain`` A string representing the cookie ``Domain``, or ``None``. If domain is ``None``, no ``Domain`` value will be sent in the cookie. ``secure`` A boolean. If it\'s ``True``, the ``secure`` flag will be sent in the cookie, if it\'s ``False``, the ``secure`` flag will not be sent in the cookie. ``httponly`` A boolean. If it\'s ``True``, the ``HttpOnly`` flag will be sent in the cookie, if it\'s ``False``, the ``HttpOnly`` flag will not be sent in the cookie. ``comment`` A string representing the cookie ``Comment`` value, or ``None``. If ``comment`` is ``None``, no ``Comment`` value will be sent in the cookie. ``expires`` A ``datetime.timedelta`` object representing an amount of time or the value ``None``. A non-``None`` value is used to generate the ``Expires`` value of the generated cookie. If ``max_age`` is not passed, but this value is not ``None``, it will influence the ``Max-Age`` header (``Max-Age`` will be \'expires_value - datetime.utcnow()\'). If this value is ``None``, the ``Expires`` cookie value will be unset (unless ``max_age`` is also passed). ``overwrite`` If this key is ``True``, before setting the cookie, unset any existing cookie.'
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) expires = (datetime.utcnow() + max_age) elif ((max_age is None) and (expires is not None)): max_age = (expires - datetime.utcnow()) value = bytes_(value, 'utf8') key = bytes_(key, 'utf8') m = Morsel(key, value) m.path = bytes_(path, 'utf8') m.domain = bytes_(domain, 'utf8') m.comment = bytes_(comment, 'utf8') m.expires = expires m.max_age = max_age m.secure = secure m.httponly = httponly self.headerlist.append(('Set-Cookie', m.serialize()))
'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 isinstance(key, text_type): key = key.encode('utf8') if (key in cookies): del cookies[key] del self.headers['Set-Cookie'] for m in cookies.values(): self.headerlist.append(('Set-Cookie', m.serialize())) elif strict: raise KeyError(('No cookie has been set with the name %r' % key))
'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')] def repl_app(environ, start_response): def repl_start_response(status, headers, exc_info=None): return start_response(status, (headers + c_headers), exc_info=exc_info) return resp(environ, repl_start_response) return repl_app
'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): new_obj = CacheControl.parse(value, type='response') self._cache_control_obj.properties.clear() self._cache_control_obj.properties.update(new_obj.properties) self._cache_control_obj.header_value = value return self._cache_control_obj
'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 cache_control.must_revalidate = True cache_control.max_age = 0 cache_control.post_check = 0 cache_control.pre_check = 0 self.expires = datetime.utcnow() if ('last-modified' not in self.headers): self.last_modified = datetime.utcnow() self.pragma = 'no-cache' else: cache_control.properties.clear() cache_control.max_age = seconds self.expires = (datetime.utcnow() + timedelta(seconds=seconds)) self.pragma = None for (name, value) in kw.items(): setattr(cache_control, name, value)
'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 = None else: self.app_iter = list(gzip_app_iter(self._app_iter)) self.content_length = sum(map(len, self._app_iter)) self.content_encoding = 'gzip'
'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 md5_digest = md5(body).digest() md5_digest = b64encode(md5_digest) md5_digest = md5_digest.replace('\n', '') md5_digest = native_(md5_digest) self.etag = md5_digest.strip('=') if set_content_md5: self.content_md5 = md5_digest
'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 = list(self.headerlist) for (i, (name, value)) in enumerate(headerlist): if (name.lower() == 'location'): if SCHEME_RE.search(value): break new_location = urlparse.urljoin(_request_uri(environ), value) headerlist[i] = (name, new_location) break return headerlist
'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 = BaseRequest(environ) headerlist = self._abs_headerlist(environ) method = environ.get('REQUEST_METHOD', 'GET') if (method in self._safe_methods): status304 = False 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): status304 = (self.last_modified <= req.if_modified_since) if status304: start_response('304 Not Modified', filter_headers(headerlist)) return EmptyResponse(self._app_iter) if (req.range and (self in req.if_range) and (self.content_range is None) and (method in ('HEAD', 'GET')) and (self.status_code == 200) and (self.content_length is not None)): content_range = req.range.content_range(self.content_length) if (content_range is None): iter_close(self._app_iter) body = bytes_(('Requested range not satisfiable: %s' % req.range)) headerlist = ([('Content-Length', str(len(body))), ('Content-Range', str(ContentRange(None, None, self.content_length))), ('Content-Type', 'text/plain')] + filter_headers(headerlist)) start_response('416 Requested Range Not Satisfiable', headerlist) if (method == 'HEAD'): return () return [body] else: app_iter = self.app_iter_range(content_range.start, content_range.stop) if (app_iter is not None): assert (content_range.start is not None) headerlist = ([('Content-Length', str((content_range.stop - content_range.start))), ('Content-Range', str(content_range))] + filter_headers(headerlist, ('content-length',))) start_response('206 Partial Content', headerlist) if (method == 'HEAD'): return EmptyResponse(app_iter) return app_iter start_response(self.status, headerlist) if (method == 'HEAD'): return EmptyResponse(self._app_iter) return self._app_iter
'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 ()): charset = field.type_options.get('charset', 'utf8') transfer_encoding = field.headers.get('Content-Transfer-Encoding', None) supported_tranfer_encoding = {'base64': binascii.a2b_base64, 'quoted-printable': binascii.a2b_qp} if PY3: if (charset == 'utf8'): decode = (lambda b: b) else: decode = (lambda b: b.encode('utf8').decode(charset)) else: decode = (lambda b: b.decode(charset)) if field.filename: field.filename = decode(field.filename) obj.add(field.name, field) else: value = field.value if (transfer_encoding in supported_tranfer_encoding): if PY3: value = value.encode('utf8') value = supported_tranfer_encoding[transfer_encoding](value) if PY3: value = value.decode('utf8') obj.add(field.name, decode(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.items(): if (key in result): if (key in multi): result[key].append(value) else: result[key] = [result[key], value] multi[key] = None else: result[key] = value return result
'Returns a dictionary where each key is associated with a list of values.'
def dict_of_lists(self):
r = {} for (key, val) in self.items(): r.setdefault(key, []).append(val) return r
'Turn a Message object into a list of WSGI-style headers.'
def parse_headers(self, message):
headers_out = [] if PY3: headers = message._headers else: headers = message.headers for full_header in headers: if (not full_header): continue if full_header[0].isspace(): if (not headers_out): raise ValueError(('First header starts with a space (%r)' % full_header)) (last_header, last_value) = headers_out.pop() value = ((last_value + ', ') + full_header.strip()) headers_out.append((last_header, value)) continue if isinstance(full_header, tuple): (header, value) = full_header else: try: (header, value) = full_header.split(':', 1) except: raise ValueError(('Invalid header: %r' % (full_header,))) value = value.strip() if (('\n' in value) or ('\r\n' in value)): value = self.MULTILINE_RE.sub(', ', value) if (header.lower() not in self.filtered_headers): headers_out.append((header, value)) return headers_out
'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) except ValueError: pass props[name] = value obj = cls(props, type=type) if updates_to: props.updated_args = (obj,) return obj
'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, strong=True):
if (value == '*'): return AnyETag if (not value): return cls([]) matches = _rx_etag.findall(value) if (not matches): return cls([value]) elif strong: return cls([t for (w, t) in matches if (not w)]) else: return cls([t for (w, t) in matches])
'Parse this from a header value.'
@classmethod def parse(cls, value):
if (not value): return cls(AnyETag) elif value.endswith(' GMT'): return IfRangeDate(parse_date(value)) else: return cls(ETagMatcher.parse(value))
'Return True if the If-Range header matches the given etag or last_modified'
def __contains__(self, resp):
return (resp.etag_strong in self.etag)
'Iter over the content of the file. You can set the `seek` parameter to read the file starting from a specific position. You can set the `limit` parameter to read the file up to specific position. Finally, you can change the number of bytes read at once by setting the `block_size` parameter.'
def app_iter_range(self, seek=None, limit=None, block_size=None):
if (block_size is None): block_size = BLOCK_SIZE if seek: self.file.seek(seek) if (limit is not None): limit -= seek try: while True: data = self.file.read((min(block_size, limit) if (limit is not None) else block_size)) if (not data): return (yield data) if (limit is not None): limit -= len(data) if (limit <= 0): return finally: self.file.close()
'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)) continue except ValueError: pass (yield (name, 1))
'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()
'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 shows up first in the `offers` list will be returned. But among matches with the same quality the match to a more specific requested type will be chosen. For example a match to text/* trumps */*. default_match (default None) is returned if there is no intersection.'
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 = (server_quality * quality) if (possible_quality < best_quality): continue elif (possible_quality == best_quality): if (matched_by.count('*') <= mask.count('*')): continue if self._match(mask, offer): best_quality = possible_quality best_offer = offer matched_by = mask return best_offer
'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.lower() == mask.lower()) elif (mask == '*/*'): return True else: assert mask.endswith('/*') mask_major = mask[:(-2)].lower() offer_major = offer.split('/', 1)[0].lower() 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(args) != 1) or kw): raise TypeError('Calling %r as a WSGI app with the wrong signature') environ = req start_response = args[0] req = self.RequestClass(environ) req.response = req.ResponseClass() try: args = self.args if self.middleware_wraps: args = ((self.middleware_wraps,) + args) resp = self.call_func(req, *args, **self.kwargs) except HTTPException as exc: resp = exc if (resp is None): resp = req.response if isinstance(resp, text_type): resp = bytes_(resp, req.charset) if isinstance(resp, bytes): body = resp resp = req.response resp.write(body) if (resp is not req.response): resp = req.response.merge_cookies(resp) return resp(environ, start_response) else: if self.middleware_wraps: args = ((self.middleware_wraps,) + args) return self.func(req, *args, **kw)
'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)