desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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 = ('-' if (seconds < 0) else '+') 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('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('O') return unicode(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 ...
'Year, 2 digits; e.g. \'99\''
def y(self):
return unicode(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 ...
'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
'A hack to get around the deprecation errors in 2.6.'
@property def message(self):
return self._message
'Returns this token as a plain string, suitable for storage. The resulting string includes the token\'s secret, so you should never send or store this string where a third party can read it.'
def to_string(self):
data = {'oauth_token': self.key, 'oauth_token_secret': self.secret} if (self.callback_confirmed is not None): data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data)
'Deserializes a token from a string like one returned by `to_string()`.'
@staticmethod def from_string(s):
if (not len(s)): raise ValueError('Invalid parameter string.') params = parse_qs(s, keep_blank_values=False) if (not len(params)): raise ValueError('Invalid parameter string.') try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_...
'Get any non-OAuth parameters.'
def get_nonoauth_parameters(self):
return dict([(k, v) for (k, v) in self.iteritems() if (not k.startswith('oauth_'))])
'Serialize as a header for an HTTPAuth request.'
def to_header(self, realm=''):
oauth_params = ((k, v) for (k, v) in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for (k, v) in oauth_params) header_params = (('%s="%s"' % (k, v)) for (k, v) in stringy_params) params_header = ', '.join(header_params) auth_header = ('OAuth realm="%s"' % realm)...
'Serialize as post data for a POST request.'
def to_postdata(self):
d = {} for (k, v) in self.iteritems(): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) return urllib.urlencode(d, True).replace('+', '%20')
'Serialize as a URL for a GET request.'
def to_url(self):
base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: query = base_url[4] query = parse_qs(query) for (k, v) in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc ...
'Return a string that contains the parameters that must be signed.'
def get_normalized_parameters(self):
items = [] for (key, value) in self.iteritems(): if (key == 'oauth_signature'): continue if isinstance(value, basestring): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeErro...
'Set the signature parameter to the result of sign.'
def sign_request(self, signature_method, consumer, token):
if (not self.is_form_encoded): self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if ('oauth_consumer_key' not in self): self['oauth_consumer_key'] = consumer.key if (token and ('oauth_token' not in self)): self['oauth_token'] = token.key self['oauth_signature_me...
'Get seconds since epoch (UTC).'
@classmethod def make_timestamp(cls):
return str(int(time.time()))
'Generate pseudorandom number.'
@classmethod def make_nonce(cls):
return str(random.randint(0, 100000000))
'Combines multiple parameter sources.'
@classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None):
if (parameters is None): parameters = {} if (headers and ('Authorization' in headers)): auth_header = headers['Authorization'] if (auth_header[:6] == 'OAuth '): auth_header = auth_header[6:] try: header_params = cls._split_header(auth_header) ...
'Turn Authorization: header into parameters.'
@staticmethod def _split_header(header):
params = {} parts = header.split(',') for param in parts: if (param.find('realm') > (-1)): continue param = param.strip() param_parts = param.split('=', 1) params[param_parts[0]] = urllib.unquote(param_parts[1].strip('"')) return params
'Turn URL string into parameters.'
@staticmethod def _split_url_string(param_str):
parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for (k, v) in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters
'Verifies an api call and checks all the parameters.'
def verify_request(self, request, consumer, token):
self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters
'Optional support for the authenticate header.'
def build_authenticate_header(self, realm=''):
return {'WWW-Authenticate': ('OAuth realm="%s"' % realm)}
'Verify the correct version of the request for this server.'
def _check_version(self, request):
version = self._get_version(request) if (version and (version != self.version)): raise Error(('OAuth version %s not supported.' % str(version)))
'Return the version of the request for this server.'
def _get_version(self, request):
try: version = request.get_parameter('oauth_version') except: version = OAUTH_VERSION return version
'Figure out the signature with some defaults.'
def _get_signature_method(self, request):
try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise ...
'Verify that timestamp is recentish.'
def _check_timestamp(self, timestamp):
timestamp = int(timestamp) now = int(time.time()) lapsed = (now - timestamp) if (lapsed > self.timestamp_threshold): raise Error(('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold...
'Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software.'
def signing_base(self, request, consumer, token):
raise NotImplementedError
'Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging.'
def sign(self, request, consumer, token):
raise NotImplementedError
'Returns whether the given signature is the correct signature for the given consumer and token signing the given request.'
def check(self, request, consumer, token, signature):
built = self.sign(request, consumer, token) return (built == signature)
'Builds the base signature string.'
def sign(self, request, consumer, token):
(key, raw) = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha) return binascii.b2a_base64(hashed.digest())[:(-1)]
'Concatenates the consumer key and secret with the token\'s secret.'
def signing_base(self, request, consumer, token):
sig = ('%s&' % escape(consumer.secret)) if token: sig = (sig + escape(token.secret)) return (sig, sig)
'add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...)'
def add_argument(self, *args, **kwargs):
chars = self.prefix_chars if ((not args) or ((len(args) == 1) and (args[0][0] not in chars))): if (args and ('dest' in kwargs)): raise ValueError('dest supplied twice for positional argument') kwargs = self._get_positional_kwargs(*args, **kwargs) else: kwar...
'error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception.'
def error(self, message):
self.print_usage(_sys.stderr) self.exit(2, (_('%s: error: %s\n') % (self.prog, message)))
'Returns true if this range can be satisfied by the resource with the given byte length.'
def satisfiable(self, length):
for (begin, end) in self.ranges: if ((end is not None) and (end >= length)): return False return True
'*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 If length is None (unknown length), then the resulting range may be (begin, None), meaning it should be served from that point. If it\'s a range with a...
def range_for_length(self, length):
if (len(self.ranges) != 1): return None (begin, end) = self.ranges[0] if (length is None): if (end is None): return (begin, end) return None if (end >= length): return None return (begin, end)
'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'
def parse(cls, header):
bytes = cls.parse_bytes(header) if (bytes is None): return None (units, ranges) = bytes if (units.lower() != 'bytes'): return None ranges = cls.bytes_to_python_ranges(ranges) if (ranges is None): return None return cls(ranges)
'Parse a Range header into (bytes, list_of_ranges). Note that the ranges are *inclusive* (like in HTTP, not like in Python typically). Will return None if the header is invalid'
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...
'Takes the output of parse_bytes and turns it into a header'
def serialize_bytes(units, ranges):
parts = [] for (begin, end) in ranges: if (end is None): if (begin >= 0): parts.append(('%s-' % begin)) else: parts.append(str(begin)) else: if (begin < 0): raise ValueError(('(%r, %r) should have a ...
'Converts the list-of-ranges from parse_bytes() to a Python-style list of ranges (non-inclusive end points) In the list of ranges, the last item can be None to indicate that it should go to the end of the file, and the first item can be negative to indicate that it should start from an offset from the end. If you give...
def bytes_to_python_ranges(ranges, length=None):
result = [] for (begin, end) in ranges: if (begin < 0): if (length is None): result.append((begin, None)) continue else: begin = (length - begin) end = length if (begin is None): begin = 0 ...
'Converts a Python-style list of ranges to what serialize_bytes expects. This is the inverse of bytes_to_python_ranges'
def python_ranges_to_bytes(ranges):
result = [] for (begin, end) in ranges: if (end is None): result.append((begin, None)) else: result.append((begin, (end + 1))) return result
'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.'
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 ('-' not in range): return None (...
'Create a dict that is a view on the given list'
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'
def from_fieldstorage(cls, fs):
obj = cls() if fs.list: for field in fs.list: 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):
result = {} for (key, value) in self.iteritems(): if (key in result): result[key].append(value) else: result[key] = [value] return result
'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: value.name = value.name.decode(self.encoding, self.errors) if value.filename: value.filename = value.filename.decode(self.encoding, self.errors) else: try: va...
'Add the key and value, not overwriting any previous value.'
def add(self, key, value):
self.multi.add(key, value)
'Return a list of all values matching the key (may be an empty list)'
def getall(self, key):
return [self._decode_value(v) for v in self.multi.getall(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(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
'The WSGI environment dictionary for this request'
def environ(self):
return self._environ_getter()
'Access the body of the request (wsgi.input) as a file-like object. If you set this value, CONTENT_LENGTH will also be updated (either set to -1, 0 if you delete the attribute, or if you set the attribute to a string then the length of the string).'
def _body_file__get(self):
return self.environ['wsgi.input']
'All the request headers as a case-insensitive dictionary-like object.'
def _headers__get(self):
if (self._headers is None): self._headers = EnvironHeaders(self.environ) return self._headers
'The URL through the host (no path)'
def host_url(self):
e = self.environ url = (e['wsgi.url_scheme'] + '://') if e.get('HTTP_HOST'): host = e['HTTP_HOST'] if (':' in host): (host, port) = host.split(':', 1) else: port = None else: host = e['SERVER_NAME'] port = e['SERVER_PORT'] if (self.envi...
'The URL including SCRIPT_NAME (no PATH_INFO or query string)'
def application_url(self):
return (self.host_url + urllib.quote(self.environ.get('SCRIPT_NAME', '')))
'The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING'
def path_url(self):
return (self.application_url + urllib.quote(self.environ.get('PATH_INFO', '')))
'The path of the request, without host or query string'
def path(self):
return (urllib.quote(self.script_name) + urllib.quote(self.path_info))
'The path of the request, without host but with query string'
def path_qs(self):
path = self.path qs = self.environ.get('QUERY_STRING') if qs: path += ('?' + qs) return path
'The full request URL, including QUERY_STRING'
def url(self):
url = self.path_url if self.environ.get('QUERY_STRING'): url += ('?' + self.environ['QUERY_STRING']) return url
'Resolve other_url relative to the request URL. If ``to_application`` is True, then resolve it relative to the URL with only SCRIPT_NAME'
def relative_url(self, other_url, to_application=False):
if to_application: url = self.application_url if (not url.endswith('/')): url += '/' else: url = self.path_url return urlparse.urljoin(url, other_url)
'\'Pops\' off the next segment of PATH_INFO, pushing it onto SCRIPT_NAME, and returning the popped segment. Returns None if there is nothing left on PATH_INFO. Does not return ``\'\'`` when there\'s an empty segment (like ``/path//path``); these segments are just ignored.'
def path_info_pop(self):
path = self.path_info if (not path): return None while path.startswith('/'): self.script_name += '/' path = path[1:] if ('/' not in path): self.script_name += path self.path_info = '' return path else: (segment, path) = path.split('/', 1) ...
'Returns the next segment on PATH_INFO, or None if there is no next segment. Doesn\'t modify the environment.'
def path_info_peek(self):
path = self.path_info if (not path): return None path = path.lstrip('/') return path.split('/', 1)[0]
'Return any *named* variables matched in the URL. Takes values from ``environ[\'wsgiorg.routing_args\']``. Systems like ``routes`` set this value.'
def _urlvars__get(self):
if ('paste.urlvars' in self.environ): return self.environ['paste.urlvars'] elif ('wsgiorg.routing_args' in self.environ): return self.environ['wsgiorg.routing_args'][1] else: result = {} self.environ['wsgiorg.routing_args'] = ((), result) return result
'Return any *positional* variables matched in the URL. Takes values from ``environ[\'wsgiorg.routing_args\']``. Systems like ``routes`` set this value.'
def _urlargs__get(self):
if ('wsgiorg.routing_args' in self.environ): return self.environ['wsgiorg.routing_args'][0] else: return ()
'Returns a boolean if X-Requested-With is present and ``XMLHttpRequest`` Note: this isn\'t set by every XMLHttpRequest request, it is only set if you are using a Javascript library that sets it (or you set the header yourself manually). Currently Prototype and jQuery are known to set this header.'
def is_xhr(self):
return (self.environ.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest')
'Host name provided in HTTP_HOST, with fall-back to SERVER_NAME'
def _host__get(self):
if ('HTTP_HOST' in self.environ): return self.environ['HTTP_HOST'] else: return ('%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ)
'Return the content of the request body.'
def _body__get(self):
try: length = int(self.environ.get('CONTENT_LENGTH', '0')) except ValueError: return '' c = self.body_file.read(length) tempfile_limit = self.request_body_tempfile_limit if (tempfile_limit and (len(c) > tempfile_limit)): fileobj = tempfile.TemporaryFile() fileobj.writ...
'Return a MultiDict containing all the variables from a POST form request. Does *not* return anything for non-POST requests or for non-form requests (returns empty dict-like object in that case).'
def str_POST(self):
env = self.environ if (self.method != 'POST'): return NoVars('Not a POST request') if ('webob._parsed_post_vars' in env): (vars, body_file) = env['webob._parsed_post_vars'] if (body_file is self.body_file): return vars if ('paste.parsed_formvars' in env): ...
'Like ``.str_POST``, but may decode values and keys'
def POST(self):
vars = self.str_POST if self.charset: vars = UnicodeMultiDict(vars, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return vars
'Return a MultiDict containing all the variables from the QUERY_STRING.'
def str_GET(self):
env = self.environ source = env.get('QUERY_STRING', '') if ('webob._parsed_query_vars' in env): (vars, qs) = env['webob._parsed_query_vars'] if (qs == source): return vars if (not source): vars = MultiDict() else: vars = MultiDict(cgi.parse_qsl(source, kee...
'Like ``.str_GET``, but may decode values and keys'
def GET(self):
vars = self.str_GET if self.charset: vars = UnicodeMultiDict(vars, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return vars
'A dictionary-like object containing both the parameters from the query string and request body.'
def str_params(self):
return NestedMultiDict(self.str_GET, self.str_POST)
'Like ``.str_params``, but may decode values and keys'
def params(self):
params = self.str_params if self.charset: params = UnicodeMultiDict(params, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return params
'Return a *plain* dictionary of cookies as found in the request.'
def str_cookies(self):
env = self.environ source = env.get('HTTP_COOKIE', '') if ('webob._parsed_cookies' in env): (vars, var_source) = env['webob._parsed_cookies'] if (var_source == source): return vars vars = {} if source: cookies = BaseCookie() cookies.load(source) fo...
'Like ``.str_cookies``, but may decode values and keys'
def cookies(self):
vars = self.str_cookies if self.charset: vars = UnicodeMultiDict(vars, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return vars
'Copy the request and environment object. This only does a shallow copy, except of wsgi.input'
def copy(self):
env = self.environ.copy() data = self.body tempfile_limit = self.request_body_tempfile_limit if (tempfile_limit and (len(data) > tempfile_limit)): fileobj = tempfile.TemporaryFile() fileobj.write(data) fileobj.seek(0) else: fileobj = StringIO(data) env['wsgi.input...
'Copies the request and environment object, but turning this request into a GET along the way. If this was a POST request (or any other verb) then it becomes GET, and the request body is thrown away.'
def copy_get(self):
env = self.environ.copy() env['wsgi.input'] = StringIO('') env['CONTENT_LENGTH'] = '0' if ('CONTENT_TYPE' in env): del env['CONTENT_TYPE'] env['REQUEST_METHOD'] = 'GET' return self.__class__(env)
'Remove headers that make the request conditional. These headers can cause the response to be 304 Not Modified, which in some cases you may not want to be possible. This does not remove headers like If-Match, which are used for conflict detection.'
def remove_conditional_headers(self, remove_encoding=True):
for key in ['HTTP_IF_MATCH', 'HTTP_IF_MODIFIED_SINCE', 'HTTP_IF_RANGE', 'HTTP_RANGE']: if (key in self.environ): del self.environ[key] if remove_encoding: if ('HTTP_ACCEPT_ENCODING' in self.environ): del self.environ['HTTP_ACCEPT_ENCODING']