index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
7,925 | webtest.app | TestApp |
Wraps a WSGI application in a more convenient interface for
testing. It uses extended version of :class:`webob.BaseRequest`
and :class:`webob.Response`.
:param app:
May be an WSGI application or Paste Deploy app,
like ``'config:filename.ini#test'``.
.. versionadded:: 2.0
It can also be an actual full URL to an http server and webtest
will proxy requests with `WSGIProxy2
<https://pypi.org/project/WSGIProxy2/>`_.
:type app:
WSGI application
:param extra_environ:
A dictionary of values that should go
into the environment for each request. These can provide a
communication channel with the application.
:type extra_environ:
dict
:param relative_to:
A directory used for file
uploads are calculated relative to this. Also ``config:``
URIs that aren't absolute.
:type relative_to:
string
:param cookiejar:
:class:`cookielib.CookieJar` alike API that keeps cookies
across requests.
:type cookiejar:
CookieJar instance
.. attribute:: cookies
A convenient shortcut for a dict of all cookies in
``cookiejar``.
:param parser_features:
Passed to BeautifulSoup when parsing responses.
:type parser_features:
string or list
:param json_encoder:
Passed to json.dumps when encoding json
:type json_encoder:
A subclass of json.JSONEncoder
:param lint:
If True (default) then check that the application is WSGI compliant
:type lint:
A boolean
| class TestApp:
"""
Wraps a WSGI application in a more convenient interface for
testing. It uses extended version of :class:`webob.BaseRequest`
and :class:`webob.Response`.
:param app:
May be an WSGI application or Paste Deploy app,
like ``'config:filename.ini#test'``.
.. versionadded:: 2.0
It can also be an actual full URL to an http server and webtest
will proxy requests with `WSGIProxy2
<https://pypi.org/project/WSGIProxy2/>`_.
:type app:
WSGI application
:param extra_environ:
A dictionary of values that should go
into the environment for each request. These can provide a
communication channel with the application.
:type extra_environ:
dict
:param relative_to:
A directory used for file
uploads are calculated relative to this. Also ``config:``
URIs that aren't absolute.
:type relative_to:
string
:param cookiejar:
:class:`cookielib.CookieJar` alike API that keeps cookies
across requests.
:type cookiejar:
CookieJar instance
.. attribute:: cookies
A convenient shortcut for a dict of all cookies in
``cookiejar``.
:param parser_features:
Passed to BeautifulSoup when parsing responses.
:type parser_features:
string or list
:param json_encoder:
Passed to json.dumps when encoding json
:type json_encoder:
A subclass of json.JSONEncoder
:param lint:
If True (default) then check that the application is WSGI compliant
:type lint:
A boolean
"""
RequestClass = TestRequest
# Tell pytest not to collect this class as tests
__test__ = False
def __init__(self, app, extra_environ=None, relative_to=None,
use_unicode=True, cookiejar=None, parser_features=None,
json_encoder=None, lint=True):
if 'WEBTEST_TARGET_URL' in os.environ:
app = os.environ['WEBTEST_TARGET_URL']
if isinstance(app, str):
if app.startswith('http'):
try:
from wsgiproxy import HostProxy
except ImportError: # pragma: no cover
raise ImportError(
'Using webtest with a real url requires WSGIProxy2. '
'Please install it with: '
'pip install WSGIProxy2')
if '#' not in app:
app += '#httplib'
url, client = app.split('#', 1)
app = HostProxy(url, client=client)
else:
from paste.deploy import loadapp
# @@: Should pick up relative_to from calling module's
# __file__
app = loadapp(app, relative_to=relative_to)
self.app = app
self.lint = lint
self.relative_to = relative_to
if extra_environ is None:
extra_environ = {}
self.extra_environ = extra_environ
self.use_unicode = use_unicode
if cookiejar is None:
cookiejar = http_cookiejar.CookieJar(policy=CookiePolicy())
self.cookiejar = cookiejar
if parser_features is None:
parser_features = 'html.parser'
self.RequestClass.ResponseClass.parser_features = parser_features
if json_encoder is None:
json_encoder = json.JSONEncoder
self.JSONEncoder = json_encoder
def get_authorization(self):
"""Allow to set the HTTP_AUTHORIZATION environ key. Value should look
like one of the following:
* ``('Basic', ('user', 'password'))``
* ``('Bearer', 'mytoken')``
* ``('JWT', 'myjwt')``
If value is None the the HTTP_AUTHORIZATION is removed
"""
return self.authorization_value
def set_authorization(self, value):
self.authorization_value = value
if value is not None:
invalid_value = (
"You should use a value like ('Basic', ('user', 'password'))"
" OR ('Bearer', 'token') OR ('JWT', 'token')"
)
if isinstance(value, (list, tuple)) and len(value) == 2:
authtype, val = value
if authtype == 'Basic' and val and \
isinstance(val, (list, tuple)):
val = ':'.join(list(val))
val = b64encode(to_bytes(val)).strip()
val = val.decode('latin1')
elif authtype in ('Bearer', 'JWT') and val and \
isinstance(val, (str, str)):
val = val.strip()
else:
raise ValueError(invalid_value)
value = str('%s %s' % (authtype, val))
else:
raise ValueError(invalid_value)
self.extra_environ.update({
'HTTP_AUTHORIZATION': value,
})
else:
if 'HTTP_AUTHORIZATION' in self.extra_environ:
del self.extra_environ['HTTP_AUTHORIZATION']
authorization = property(get_authorization, set_authorization)
@property
def cookies(self):
return {cookie.name: cookie.value for cookie in self.cookiejar}
def set_cookie(self, name, value):
"""
Sets a cookie to be passed through with requests.
"""
cookie_domain = self.extra_environ.get('HTTP_HOST', '.localhost')
cookie_domain = cookie_domain.split(':', 1)[0]
if '.' not in cookie_domain:
cookie_domain = "%s.local" % cookie_domain
value = escape_cookie_value(value)
cookie = http_cookiejar.Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain=cookie_domain,
domain_specified=True,
domain_initial_dot=False,
path='/',
path_specified=True,
secure=False,
expires=None,
discard=False,
comment=None,
comment_url=None,
rest=None
)
self.cookiejar.set_cookie(cookie)
def reset(self):
"""
Resets the state of the application; currently just clears
saved cookies.
"""
self.cookiejar.clear()
def set_parser_features(self, parser_features):
"""
Changes the parser used by BeautifulSoup. See its documentation to
know the supported parsers.
"""
self.RequestClass.ResponseClass.parser_features = parser_features
def get(self, url, params=None, headers=None, extra_environ=None,
status=None, expect_errors=False, xhr=False):
"""
Do a GET request given the url path.
:param params:
A query string, or a dictionary that will be encoded
into a query string. You may also include a URL query
string on the ``url``.
:param headers:
Extra headers to send.
:type headers:
dictionary
:param extra_environ:
Environmental variables that should be added to the request.
:type extra_environ:
dictionary
:param status:
The HTTP status code you expect in response (if not 200 or 3xx).
You can also use a wildcard, like ``'3*'`` or ``'*'``.
:type status:
integer or string
:param expect_errors:
If this is False, then if anything is written to
environ ``wsgi.errors`` it will be an error.
If it is True, then non-200/3xx responses are also okay.
:type expect_errors:
boolean
:param xhr:
If this is true, then marks response as ajax. The same as
headers={'X-REQUESTED-WITH': 'XMLHttpRequest', }
:type xhr:
boolean
:returns: :class:`webtest.TestResponse` instance.
"""
environ = self._make_environ(extra_environ)
url = str(url)
url = self._remove_fragment(url)
if params:
url = utils.build_params(url, params)
if '?' in url:
url, environ['QUERY_STRING'] = url.split('?', 1)
else:
environ['QUERY_STRING'] = ''
req = self.RequestClass.blank(url, environ)
if xhr:
headers = self._add_xhr_header(headers)
if headers:
req.headers.update(headers)
return self.do_request(req, status=status,
expect_errors=expect_errors)
def post(self, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a POST request. Similar to :meth:`~webtest.TestApp.get`.
:param params:
Are put in the body of the request. If params is an
iterator, it will be urlencoded. If it is a string, it will not
be encoded, but placed in the body directly.
Can be a :class:`python:collections.OrderedDict` with
:class:`webtest.forms.Upload` fields included::
app.post('/myurl', collections.OrderedDict([
('textfield1', 'value1'),
('uploadfield', webapp.Upload('filename.txt', 'contents'),
('textfield2', 'value2')])))
:param upload_files:
It should be a list of ``(fieldname, filename, file_content)``.
You can also use just ``(fieldname, filename)`` and the file
contents will be read from disk.
:type upload_files:
list
:param content_type:
HTTP content type, for example `application/json`.
:type content_type:
string
:param xhr:
If this is true, then marks response as ajax. The same as
headers={'X-REQUESTED-WITH': 'XMLHttpRequest', }
:type xhr:
boolean
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('POST', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=upload_files,
expect_errors=expect_errors,
content_type=content_type)
def put(self, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a PUT request. Similar to :meth:`~webtest.TestApp.post`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('PUT', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=upload_files,
expect_errors=expect_errors,
content_type=content_type,
)
def patch(self, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a PATCH request. Similar to :meth:`~webtest.TestApp.post`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('PATCH', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=upload_files,
expect_errors=expect_errors,
content_type=content_type)
def delete(self, url, params='', headers=None,
extra_environ=None, status=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a DELETE request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('DELETE', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=None,
expect_errors=expect_errors,
content_type=content_type)
def options(self, url, headers=None, extra_environ=None,
status=None, expect_errors=False, xhr=False):
"""
Do a OPTIONS request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('OPTIONS', url, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=None,
expect_errors=expect_errors)
def head(self, url, params=None, headers=None, extra_environ=None,
status=None, expect_errors=False, xhr=False):
"""
Do a HEAD request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
"""
if params:
url = utils.build_params(url, params)
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('HEAD', url, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=None,
expect_errors=expect_errors)
post_json = utils.json_method('POST')
put_json = utils.json_method('PUT')
patch_json = utils.json_method('PATCH')
delete_json = utils.json_method('DELETE')
def encode_multipart(self, params, files):
"""
Encodes a set of parameters (typically a name/value list) and
a set of files (a list of (name, filename, file_body, mimetype)) into a
typical POST body, returning the (content_type, body).
"""
boundary = to_bytes(str(random.random()))[2:]
boundary = b'----------a_BoUnDaRy' + boundary + b'$'
lines = []
def _append_file(file_info):
key, filename, value, fcontent = self._get_file_info(file_info)
if isinstance(key, str):
try:
key = key.encode('ascii')
except: # pragma: no cover
raise # file name must be ascii
if isinstance(filename, str):
try:
filename = filename.encode('utf8')
except: # pragma: no cover
raise # file name must be ascii or utf8
if not fcontent:
fcontent = mimetypes.guess_type(filename.decode('utf8'))[0]
fcontent = to_bytes(fcontent)
fcontent = fcontent or b'application/octet-stream'
lines.extend([
b'--' + boundary,
b'Content-Disposition: form-data; ' +
b'name="' + key + b'"; filename="' + filename + b'"',
b'Content-Type: ' + fcontent, b'', value])
for key, value in params:
if isinstance(key, str):
try:
key = key.encode('ascii')
except: # pragma: no cover
raise # field name are always ascii
if isinstance(value, forms.File):
if value.value:
_append_file([key] + list(value.value))
else:
# If no file was uploaded simulate an empty file with no
# name like real browsers do:
_append_file([key, b'', b''])
elif isinstance(value, forms.Upload):
file_info = [key, value.filename]
if value.content is not None:
file_info.append(value.content)
if value.content_type is not None:
file_info.append(value.content_type)
_append_file(file_info)
else:
if isinstance(value, int):
value = str(value).encode('utf8')
elif isinstance(value, str):
value = value.encode('utf8')
elif not isinstance(value, (bytes, str)):
raise ValueError((
'Value for field {} is a {} ({}). '
'It must be str, bytes or an int'
).format(key, type(value), value))
lines.extend([
b'--' + boundary,
b'Content-Disposition: form-data; name="' + key + b'"',
b'', value])
for file_info in files:
_append_file(file_info)
lines.extend([b'--' + boundary + b'--', b''])
body = b'\r\n'.join(lines)
boundary = boundary.decode('ascii')
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body
def request(self, url_or_req, status=None, expect_errors=False,
**req_params):
"""
Creates and executes a request. You may either pass in an
instantiated :class:`TestRequest` object, or you may pass in a
URL and keyword arguments to be passed to
:meth:`TestRequest.blank`.
You can use this to run a request without the intermediary
functioning of :meth:`TestApp.get` etc. For instance, to
test a WebDAV method::
resp = app.request('/new-col', method='MKCOL')
Note that the request won't have a body unless you specify it,
like::
resp = app.request('/test.txt', method='PUT', body='test')
You can use :class:`webtest.TestRequest`::
req = webtest.TestRequest.blank('/url/', method='GET')
resp = app.do_request(req)
"""
if isinstance(url_or_req, str):
url_or_req = str(url_or_req)
for (k, v) in req_params.items():
if isinstance(v, str):
req_params[k] = str(v)
if isinstance(url_or_req, str):
req = self.RequestClass.blank(url_or_req, **req_params)
else:
req = url_or_req.copy()
for name, value in req_params.items():
setattr(req, name, value)
req.environ['paste.throw_errors'] = True
for name, value in self.extra_environ.items():
req.environ.setdefault(name, value)
return self.do_request(req,
status=status,
expect_errors=expect_errors,
)
def do_request(self, req, status=None, expect_errors=None):
"""
Executes the given webob Request (``req``), with the expected
``status``. Generally :meth:`~webtest.TestApp.get` and
:meth:`~webtest.TestApp.post` are used instead.
To use this::
req = webtest.TestRequest.blank('url', ...args...)
resp = app.do_request(req)
.. note::
You can pass any keyword arguments to
``TestRequest.blank()``, which will be set on the request.
These can be arguments like ``content_type``, ``accept``, etc.
"""
errors = StringIO()
req.environ['wsgi.errors'] = errors
script_name = req.environ.get('SCRIPT_NAME', '')
if script_name and req.path_info.startswith(script_name):
req.path_info = req.path_info[len(script_name):]
# set framework hooks
req.environ['paste.testing'] = True
req.environ['paste.testing_variables'] = {}
# set request cookies
self.cookiejar.add_cookie_header(utils._RequestCookieAdapter(req))
# verify wsgi compatibility
app = lint.middleware(self.app) if self.lint else self.app
# FIXME: should it be an option to not catch exc_info?
res = req.get_response(app, catch_exc_info=True)
# be sure to decode the content
res.decode_content()
# set a few handy attributes
res._use_unicode = self.use_unicode
res.request = req
res.app = app
res.test_app = self
# We do this to make sure the app_iter is exhausted:
try:
res.body
except TypeError: # pragma: no cover
pass
res.errors = errors.getvalue()
for name, value in req.environ['paste.testing_variables'].items():
if hasattr(res, name):
raise ValueError(
"paste.testing_variables contains the variable %r, but "
"the response object already has an attribute by that "
"name" % name)
setattr(res, name, value)
if not expect_errors:
self._check_status(status, res)
self._check_errors(res)
# merge cookies back in
self.cookiejar.extract_cookies(utils._ResponseCookieAdapter(res),
utils._RequestCookieAdapter(req))
return res
def _check_status(self, status, res):
if status == '*':
return
res_status = res.status
if (isinstance(status, str) and '*' in status):
if re.match(fnmatch.translate(status), res_status, re.I):
return
if isinstance(status, str):
if status == res_status:
return
if isinstance(status, (list, tuple)):
if res.status_int not in status:
raise AppError(
"Bad response: %s (not one of %s for %s)\n%s",
res_status, ', '.join(map(str, status)),
res.request.url, res)
return
if status is None:
if res.status_int >= 200 and res.status_int < 400:
return
raise AppError(
"Bad response: %s (not 200 OK or 3xx redirect for %s)\n%s",
res_status, res.request.url,
res)
if status != res.status_int:
raise AppError(
"Bad response: %s (not %s)\n%s", res_status, status, res)
def _check_errors(self, res):
errors = res.errors
if errors:
raise AppError(
"Application had errors logged:\n%s", errors)
def _make_environ(self, extra_environ=None):
environ = self.extra_environ.copy()
environ['paste.throw_errors'] = True
if extra_environ:
environ.update(extra_environ)
return environ
def _remove_fragment(self, url):
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
return urlparse.urlunsplit((scheme, netloc, path, query, ""))
def _gen_request(self, method, url, params=utils.NoDefault,
headers=None, extra_environ=None, status=None,
upload_files=None, expect_errors=False,
content_type=None):
"""
Do a generic request.
"""
environ = self._make_environ(extra_environ)
inline_uploads = []
# this supports OrderedDict
if isinstance(params, dict) or hasattr(params, 'items'):
params = list(params.items())
if isinstance(params, (list, tuple)):
inline_uploads = [v for (k, v) in params
if isinstance(v, (forms.File, forms.Upload))]
if len(inline_uploads) > 0:
content_type, params = self.encode_multipart(
params, upload_files or ())
environ['CONTENT_TYPE'] = content_type
else:
params = utils.encode_params(params, content_type)
if upload_files or \
(content_type and
to_bytes(content_type).startswith(b'multipart')):
params = urlparse.parse_qsl(params, keep_blank_values=True)
content_type, params = self.encode_multipart(
params, upload_files or ())
environ['CONTENT_TYPE'] = content_type
elif params:
environ.setdefault('CONTENT_TYPE',
'application/x-www-form-urlencoded')
if content_type is not None:
environ['CONTENT_TYPE'] = content_type
environ['REQUEST_METHOD'] = str(method)
url = str(url)
url = self._remove_fragment(url)
req = self.RequestClass.blank(url, environ)
if isinstance(params, str):
params = params.encode(req.charset or 'utf8')
req.environ['wsgi.input'] = BytesIO(params)
req.content_length = len(params)
if headers:
req.headers.update(headers)
return self.do_request(req, status=status,
expect_errors=expect_errors)
def _get_file_info(self, file_info):
if len(file_info) == 2:
# It only has a filename
filename = file_info[1]
if self.relative_to:
filename = os.path.join(self.relative_to, filename)
f = open(filename, 'rb')
content = f.read()
f.close()
return (file_info[0], filename, content, None)
elif 3 <= len(file_info) <= 4:
content = file_info[2]
if not isinstance(content, bytes):
raise ValueError('File content must be %s not %s'
% (bytes, type(content)))
if len(file_info) == 3:
return tuple(file_info) + (None,)
else:
return file_info
else:
raise ValueError(
"upload_files need to be a list of tuples of (fieldname, "
"filename, filecontent, mimetype) or (fieldname, "
"filename, filecontent) or (fieldname, filename); "
"you gave: %r"
% repr(file_info)[:100])
@staticmethod
def _add_xhr_header(headers):
headers = headers or {}
# if remove str we will be have an error in lint.middleware
headers.update({'X-REQUESTED-WITH': 'XMLHttpRequest'})
return headers
| (app, extra_environ=None, relative_to=None, use_unicode=True, cookiejar=None, parser_features=None, json_encoder=None, lint=True) |
7,926 | webtest.app | __init__ | null | def __init__(self, app, extra_environ=None, relative_to=None,
use_unicode=True, cookiejar=None, parser_features=None,
json_encoder=None, lint=True):
if 'WEBTEST_TARGET_URL' in os.environ:
app = os.environ['WEBTEST_TARGET_URL']
if isinstance(app, str):
if app.startswith('http'):
try:
from wsgiproxy import HostProxy
except ImportError: # pragma: no cover
raise ImportError(
'Using webtest with a real url requires WSGIProxy2. '
'Please install it with: '
'pip install WSGIProxy2')
if '#' not in app:
app += '#httplib'
url, client = app.split('#', 1)
app = HostProxy(url, client=client)
else:
from paste.deploy import loadapp
# @@: Should pick up relative_to from calling module's
# __file__
app = loadapp(app, relative_to=relative_to)
self.app = app
self.lint = lint
self.relative_to = relative_to
if extra_environ is None:
extra_environ = {}
self.extra_environ = extra_environ
self.use_unicode = use_unicode
if cookiejar is None:
cookiejar = http_cookiejar.CookieJar(policy=CookiePolicy())
self.cookiejar = cookiejar
if parser_features is None:
parser_features = 'html.parser'
self.RequestClass.ResponseClass.parser_features = parser_features
if json_encoder is None:
json_encoder = json.JSONEncoder
self.JSONEncoder = json_encoder
| (self, app, extra_environ=None, relative_to=None, use_unicode=True, cookiejar=None, parser_features=None, json_encoder=None, lint=True) |
7,927 | webtest.app | _add_xhr_header | null | @staticmethod
def _add_xhr_header(headers):
headers = headers or {}
# if remove str we will be have an error in lint.middleware
headers.update({'X-REQUESTED-WITH': 'XMLHttpRequest'})
return headers
| (headers) |
7,928 | webtest.app | _check_errors | null | def _check_errors(self, res):
errors = res.errors
if errors:
raise AppError(
"Application had errors logged:\n%s", errors)
| (self, res) |
7,929 | webtest.app | _check_status | null | def _check_status(self, status, res):
if status == '*':
return
res_status = res.status
if (isinstance(status, str) and '*' in status):
if re.match(fnmatch.translate(status), res_status, re.I):
return
if isinstance(status, str):
if status == res_status:
return
if isinstance(status, (list, tuple)):
if res.status_int not in status:
raise AppError(
"Bad response: %s (not one of %s for %s)\n%s",
res_status, ', '.join(map(str, status)),
res.request.url, res)
return
if status is None:
if res.status_int >= 200 and res.status_int < 400:
return
raise AppError(
"Bad response: %s (not 200 OK or 3xx redirect for %s)\n%s",
res_status, res.request.url,
res)
if status != res.status_int:
raise AppError(
"Bad response: %s (not %s)\n%s", res_status, status, res)
| (self, status, res) |
7,930 | webtest.app | _gen_request |
Do a generic request.
| def _gen_request(self, method, url, params=utils.NoDefault,
headers=None, extra_environ=None, status=None,
upload_files=None, expect_errors=False,
content_type=None):
"""
Do a generic request.
"""
environ = self._make_environ(extra_environ)
inline_uploads = []
# this supports OrderedDict
if isinstance(params, dict) or hasattr(params, 'items'):
params = list(params.items())
if isinstance(params, (list, tuple)):
inline_uploads = [v for (k, v) in params
if isinstance(v, (forms.File, forms.Upload))]
if len(inline_uploads) > 0:
content_type, params = self.encode_multipart(
params, upload_files or ())
environ['CONTENT_TYPE'] = content_type
else:
params = utils.encode_params(params, content_type)
if upload_files or \
(content_type and
to_bytes(content_type).startswith(b'multipart')):
params = urlparse.parse_qsl(params, keep_blank_values=True)
content_type, params = self.encode_multipart(
params, upload_files or ())
environ['CONTENT_TYPE'] = content_type
elif params:
environ.setdefault('CONTENT_TYPE',
'application/x-www-form-urlencoded')
if content_type is not None:
environ['CONTENT_TYPE'] = content_type
environ['REQUEST_METHOD'] = str(method)
url = str(url)
url = self._remove_fragment(url)
req = self.RequestClass.blank(url, environ)
if isinstance(params, str):
params = params.encode(req.charset or 'utf8')
req.environ['wsgi.input'] = BytesIO(params)
req.content_length = len(params)
if headers:
req.headers.update(headers)
return self.do_request(req, status=status,
expect_errors=expect_errors)
| (self, method, url, params=<NoDefault>, headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None) |
7,931 | webtest.app | _get_file_info | null | def _get_file_info(self, file_info):
if len(file_info) == 2:
# It only has a filename
filename = file_info[1]
if self.relative_to:
filename = os.path.join(self.relative_to, filename)
f = open(filename, 'rb')
content = f.read()
f.close()
return (file_info[0], filename, content, None)
elif 3 <= len(file_info) <= 4:
content = file_info[2]
if not isinstance(content, bytes):
raise ValueError('File content must be %s not %s'
% (bytes, type(content)))
if len(file_info) == 3:
return tuple(file_info) + (None,)
else:
return file_info
else:
raise ValueError(
"upload_files need to be a list of tuples of (fieldname, "
"filename, filecontent, mimetype) or (fieldname, "
"filename, filecontent) or (fieldname, filename); "
"you gave: %r"
% repr(file_info)[:100])
| (self, file_info) |
7,932 | webtest.app | _make_environ | null | def _make_environ(self, extra_environ=None):
environ = self.extra_environ.copy()
environ['paste.throw_errors'] = True
if extra_environ:
environ.update(extra_environ)
return environ
| (self, extra_environ=None) |
7,933 | webtest.app | _remove_fragment | null | def _remove_fragment(self, url):
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
return urlparse.urlunsplit((scheme, netloc, path, query, ""))
| (self, url) |
7,934 | webtest.app | delete |
Do a DELETE request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
| def delete(self, url, params='', headers=None,
extra_environ=None, status=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a DELETE request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('DELETE', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=None,
expect_errors=expect_errors,
content_type=content_type)
| (self, url, params='', headers=None, extra_environ=None, status=None, expect_errors=False, content_type=None, xhr=False) |
7,935 | webtest.utils | delete_json | Do a DELETE request. Very like the
:class:`~webtest.TestApp.delete` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
| def json_method(method):
"""Do a %(method)s request. Very like the
:class:`~webtest.TestApp.%(lmethod)s` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
"""
def wrapper(self, url, params=NoDefault, **kw):
kw.setdefault('content_type', 'application/json')
if params is not NoDefault:
params = dumps(params, cls=self.JSONEncoder)
kw.update(
params=params,
upload_files=None,
)
return self._gen_request(method, url, **kw)
subst = dict(lmethod=method.lower(), method=method)
try:
wrapper.__doc__ = json_method.__doc__ % subst
except TypeError:
pass
wrapper.__name__ = str('%(lmethod)s_json' % subst)
return wrapper
| (self, url, params=<NoDefault>, **kw) |
7,936 | webtest.app | do_request |
Executes the given webob Request (``req``), with the expected
``status``. Generally :meth:`~webtest.TestApp.get` and
:meth:`~webtest.TestApp.post` are used instead.
To use this::
req = webtest.TestRequest.blank('url', ...args...)
resp = app.do_request(req)
.. note::
You can pass any keyword arguments to
``TestRequest.blank()``, which will be set on the request.
These can be arguments like ``content_type``, ``accept``, etc.
| def do_request(self, req, status=None, expect_errors=None):
"""
Executes the given webob Request (``req``), with the expected
``status``. Generally :meth:`~webtest.TestApp.get` and
:meth:`~webtest.TestApp.post` are used instead.
To use this::
req = webtest.TestRequest.blank('url', ...args...)
resp = app.do_request(req)
.. note::
You can pass any keyword arguments to
``TestRequest.blank()``, which will be set on the request.
These can be arguments like ``content_type``, ``accept``, etc.
"""
errors = StringIO()
req.environ['wsgi.errors'] = errors
script_name = req.environ.get('SCRIPT_NAME', '')
if script_name and req.path_info.startswith(script_name):
req.path_info = req.path_info[len(script_name):]
# set framework hooks
req.environ['paste.testing'] = True
req.environ['paste.testing_variables'] = {}
# set request cookies
self.cookiejar.add_cookie_header(utils._RequestCookieAdapter(req))
# verify wsgi compatibility
app = lint.middleware(self.app) if self.lint else self.app
# FIXME: should it be an option to not catch exc_info?
res = req.get_response(app, catch_exc_info=True)
# be sure to decode the content
res.decode_content()
# set a few handy attributes
res._use_unicode = self.use_unicode
res.request = req
res.app = app
res.test_app = self
# We do this to make sure the app_iter is exhausted:
try:
res.body
except TypeError: # pragma: no cover
pass
res.errors = errors.getvalue()
for name, value in req.environ['paste.testing_variables'].items():
if hasattr(res, name):
raise ValueError(
"paste.testing_variables contains the variable %r, but "
"the response object already has an attribute by that "
"name" % name)
setattr(res, name, value)
if not expect_errors:
self._check_status(status, res)
self._check_errors(res)
# merge cookies back in
self.cookiejar.extract_cookies(utils._ResponseCookieAdapter(res),
utils._RequestCookieAdapter(req))
return res
| (self, req, status=None, expect_errors=None) |
7,937 | webtest.app | encode_multipart |
Encodes a set of parameters (typically a name/value list) and
a set of files (a list of (name, filename, file_body, mimetype)) into a
typical POST body, returning the (content_type, body).
| def encode_multipart(self, params, files):
"""
Encodes a set of parameters (typically a name/value list) and
a set of files (a list of (name, filename, file_body, mimetype)) into a
typical POST body, returning the (content_type, body).
"""
boundary = to_bytes(str(random.random()))[2:]
boundary = b'----------a_BoUnDaRy' + boundary + b'$'
lines = []
def _append_file(file_info):
key, filename, value, fcontent = self._get_file_info(file_info)
if isinstance(key, str):
try:
key = key.encode('ascii')
except: # pragma: no cover
raise # file name must be ascii
if isinstance(filename, str):
try:
filename = filename.encode('utf8')
except: # pragma: no cover
raise # file name must be ascii or utf8
if not fcontent:
fcontent = mimetypes.guess_type(filename.decode('utf8'))[0]
fcontent = to_bytes(fcontent)
fcontent = fcontent or b'application/octet-stream'
lines.extend([
b'--' + boundary,
b'Content-Disposition: form-data; ' +
b'name="' + key + b'"; filename="' + filename + b'"',
b'Content-Type: ' + fcontent, b'', value])
for key, value in params:
if isinstance(key, str):
try:
key = key.encode('ascii')
except: # pragma: no cover
raise # field name are always ascii
if isinstance(value, forms.File):
if value.value:
_append_file([key] + list(value.value))
else:
# If no file was uploaded simulate an empty file with no
# name like real browsers do:
_append_file([key, b'', b''])
elif isinstance(value, forms.Upload):
file_info = [key, value.filename]
if value.content is not None:
file_info.append(value.content)
if value.content_type is not None:
file_info.append(value.content_type)
_append_file(file_info)
else:
if isinstance(value, int):
value = str(value).encode('utf8')
elif isinstance(value, str):
value = value.encode('utf8')
elif not isinstance(value, (bytes, str)):
raise ValueError((
'Value for field {} is a {} ({}). '
'It must be str, bytes or an int'
).format(key, type(value), value))
lines.extend([
b'--' + boundary,
b'Content-Disposition: form-data; name="' + key + b'"',
b'', value])
for file_info in files:
_append_file(file_info)
lines.extend([b'--' + boundary + b'--', b''])
body = b'\r\n'.join(lines)
boundary = boundary.decode('ascii')
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body
| (self, params, files) |
7,938 | webtest.app | get |
Do a GET request given the url path.
:param params:
A query string, or a dictionary that will be encoded
into a query string. You may also include a URL query
string on the ``url``.
:param headers:
Extra headers to send.
:type headers:
dictionary
:param extra_environ:
Environmental variables that should be added to the request.
:type extra_environ:
dictionary
:param status:
The HTTP status code you expect in response (if not 200 or 3xx).
You can also use a wildcard, like ``'3*'`` or ``'*'``.
:type status:
integer or string
:param expect_errors:
If this is False, then if anything is written to
environ ``wsgi.errors`` it will be an error.
If it is True, then non-200/3xx responses are also okay.
:type expect_errors:
boolean
:param xhr:
If this is true, then marks response as ajax. The same as
headers={'X-REQUESTED-WITH': 'XMLHttpRequest', }
:type xhr:
boolean
:returns: :class:`webtest.TestResponse` instance.
| def get(self, url, params=None, headers=None, extra_environ=None,
status=None, expect_errors=False, xhr=False):
"""
Do a GET request given the url path.
:param params:
A query string, or a dictionary that will be encoded
into a query string. You may also include a URL query
string on the ``url``.
:param headers:
Extra headers to send.
:type headers:
dictionary
:param extra_environ:
Environmental variables that should be added to the request.
:type extra_environ:
dictionary
:param status:
The HTTP status code you expect in response (if not 200 or 3xx).
You can also use a wildcard, like ``'3*'`` or ``'*'``.
:type status:
integer or string
:param expect_errors:
If this is False, then if anything is written to
environ ``wsgi.errors`` it will be an error.
If it is True, then non-200/3xx responses are also okay.
:type expect_errors:
boolean
:param xhr:
If this is true, then marks response as ajax. The same as
headers={'X-REQUESTED-WITH': 'XMLHttpRequest', }
:type xhr:
boolean
:returns: :class:`webtest.TestResponse` instance.
"""
environ = self._make_environ(extra_environ)
url = str(url)
url = self._remove_fragment(url)
if params:
url = utils.build_params(url, params)
if '?' in url:
url, environ['QUERY_STRING'] = url.split('?', 1)
else:
environ['QUERY_STRING'] = ''
req = self.RequestClass.blank(url, environ)
if xhr:
headers = self._add_xhr_header(headers)
if headers:
req.headers.update(headers)
return self.do_request(req, status=status,
expect_errors=expect_errors)
| (self, url, params=None, headers=None, extra_environ=None, status=None, expect_errors=False, xhr=False) |
7,939 | webtest.app | get_authorization | Allow to set the HTTP_AUTHORIZATION environ key. Value should look
like one of the following:
* ``('Basic', ('user', 'password'))``
* ``('Bearer', 'mytoken')``
* ``('JWT', 'myjwt')``
If value is None the the HTTP_AUTHORIZATION is removed
| def get_authorization(self):
"""Allow to set the HTTP_AUTHORIZATION environ key. Value should look
like one of the following:
* ``('Basic', ('user', 'password'))``
* ``('Bearer', 'mytoken')``
* ``('JWT', 'myjwt')``
If value is None the the HTTP_AUTHORIZATION is removed
"""
return self.authorization_value
| (self) |
7,940 | webtest.app | head |
Do a HEAD request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
| def head(self, url, params=None, headers=None, extra_environ=None,
status=None, expect_errors=False, xhr=False):
"""
Do a HEAD request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
"""
if params:
url = utils.build_params(url, params)
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('HEAD', url, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=None,
expect_errors=expect_errors)
| (self, url, params=None, headers=None, extra_environ=None, status=None, expect_errors=False, xhr=False) |
7,941 | webtest.app | options |
Do a OPTIONS request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
| def options(self, url, headers=None, extra_environ=None,
status=None, expect_errors=False, xhr=False):
"""
Do a OPTIONS request. Similar to :meth:`~webtest.TestApp.get`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('OPTIONS', url, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=None,
expect_errors=expect_errors)
| (self, url, headers=None, extra_environ=None, status=None, expect_errors=False, xhr=False) |
7,942 | webtest.app | patch |
Do a PATCH request. Similar to :meth:`~webtest.TestApp.post`.
:returns: :class:`webtest.TestResponse` instance.
| def patch(self, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a PATCH request. Similar to :meth:`~webtest.TestApp.post`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('PATCH', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=upload_files,
expect_errors=expect_errors,
content_type=content_type)
| (self, url, params='', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None, xhr=False) |
7,943 | webtest.utils | patch_json | Do a PATCH request. Very like the
:class:`~webtest.TestApp.patch` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
| def json_method(method):
"""Do a %(method)s request. Very like the
:class:`~webtest.TestApp.%(lmethod)s` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
"""
def wrapper(self, url, params=NoDefault, **kw):
kw.setdefault('content_type', 'application/json')
if params is not NoDefault:
params = dumps(params, cls=self.JSONEncoder)
kw.update(
params=params,
upload_files=None,
)
return self._gen_request(method, url, **kw)
subst = dict(lmethod=method.lower(), method=method)
try:
wrapper.__doc__ = json_method.__doc__ % subst
except TypeError:
pass
wrapper.__name__ = str('%(lmethod)s_json' % subst)
return wrapper
| (self, url, params=<NoDefault>, **kw) |
7,944 | webtest.app | post |
Do a POST request. Similar to :meth:`~webtest.TestApp.get`.
:param params:
Are put in the body of the request. If params is an
iterator, it will be urlencoded. If it is a string, it will not
be encoded, but placed in the body directly.
Can be a :class:`python:collections.OrderedDict` with
:class:`webtest.forms.Upload` fields included::
app.post('/myurl', collections.OrderedDict([
('textfield1', 'value1'),
('uploadfield', webapp.Upload('filename.txt', 'contents'),
('textfield2', 'value2')])))
:param upload_files:
It should be a list of ``(fieldname, filename, file_content)``.
You can also use just ``(fieldname, filename)`` and the file
contents will be read from disk.
:type upload_files:
list
:param content_type:
HTTP content type, for example `application/json`.
:type content_type:
string
:param xhr:
If this is true, then marks response as ajax. The same as
headers={'X-REQUESTED-WITH': 'XMLHttpRequest', }
:type xhr:
boolean
:returns: :class:`webtest.TestResponse` instance.
| def post(self, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a POST request. Similar to :meth:`~webtest.TestApp.get`.
:param params:
Are put in the body of the request. If params is an
iterator, it will be urlencoded. If it is a string, it will not
be encoded, but placed in the body directly.
Can be a :class:`python:collections.OrderedDict` with
:class:`webtest.forms.Upload` fields included::
app.post('/myurl', collections.OrderedDict([
('textfield1', 'value1'),
('uploadfield', webapp.Upload('filename.txt', 'contents'),
('textfield2', 'value2')])))
:param upload_files:
It should be a list of ``(fieldname, filename, file_content)``.
You can also use just ``(fieldname, filename)`` and the file
contents will be read from disk.
:type upload_files:
list
:param content_type:
HTTP content type, for example `application/json`.
:type content_type:
string
:param xhr:
If this is true, then marks response as ajax. The same as
headers={'X-REQUESTED-WITH': 'XMLHttpRequest', }
:type xhr:
boolean
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('POST', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=upload_files,
expect_errors=expect_errors,
content_type=content_type)
| (self, url, params='', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None, xhr=False) |
7,945 | webtest.utils | post_json | Do a POST request. Very like the
:class:`~webtest.TestApp.post` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
| def json_method(method):
"""Do a %(method)s request. Very like the
:class:`~webtest.TestApp.%(lmethod)s` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
"""
def wrapper(self, url, params=NoDefault, **kw):
kw.setdefault('content_type', 'application/json')
if params is not NoDefault:
params = dumps(params, cls=self.JSONEncoder)
kw.update(
params=params,
upload_files=None,
)
return self._gen_request(method, url, **kw)
subst = dict(lmethod=method.lower(), method=method)
try:
wrapper.__doc__ = json_method.__doc__ % subst
except TypeError:
pass
wrapper.__name__ = str('%(lmethod)s_json' % subst)
return wrapper
| (self, url, params=<NoDefault>, **kw) |
7,946 | webtest.app | put |
Do a PUT request. Similar to :meth:`~webtest.TestApp.post`.
:returns: :class:`webtest.TestResponse` instance.
| def put(self, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False,
content_type=None, xhr=False):
"""
Do a PUT request. Similar to :meth:`~webtest.TestApp.post`.
:returns: :class:`webtest.TestResponse` instance.
"""
if xhr:
headers = self._add_xhr_header(headers)
return self._gen_request('PUT', url, params=params, headers=headers,
extra_environ=extra_environ, status=status,
upload_files=upload_files,
expect_errors=expect_errors,
content_type=content_type,
)
| (self, url, params='', headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None, xhr=False) |
7,947 | webtest.utils | put_json | Do a PUT request. Very like the
:class:`~webtest.TestApp.put` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
| def json_method(method):
"""Do a %(method)s request. Very like the
:class:`~webtest.TestApp.%(lmethod)s` method.
``params`` are dumped to json and put in the body of the request.
Content-Type is set to ``application/json``.
Returns a :class:`webtest.TestResponse` object.
"""
def wrapper(self, url, params=NoDefault, **kw):
kw.setdefault('content_type', 'application/json')
if params is not NoDefault:
params = dumps(params, cls=self.JSONEncoder)
kw.update(
params=params,
upload_files=None,
)
return self._gen_request(method, url, **kw)
subst = dict(lmethod=method.lower(), method=method)
try:
wrapper.__doc__ = json_method.__doc__ % subst
except TypeError:
pass
wrapper.__name__ = str('%(lmethod)s_json' % subst)
return wrapper
| (self, url, params=<NoDefault>, **kw) |
7,948 | webtest.app | request |
Creates and executes a request. You may either pass in an
instantiated :class:`TestRequest` object, or you may pass in a
URL and keyword arguments to be passed to
:meth:`TestRequest.blank`.
You can use this to run a request without the intermediary
functioning of :meth:`TestApp.get` etc. For instance, to
test a WebDAV method::
resp = app.request('/new-col', method='MKCOL')
Note that the request won't have a body unless you specify it,
like::
resp = app.request('/test.txt', method='PUT', body='test')
You can use :class:`webtest.TestRequest`::
req = webtest.TestRequest.blank('/url/', method='GET')
resp = app.do_request(req)
| def request(self, url_or_req, status=None, expect_errors=False,
**req_params):
"""
Creates and executes a request. You may either pass in an
instantiated :class:`TestRequest` object, or you may pass in a
URL and keyword arguments to be passed to
:meth:`TestRequest.blank`.
You can use this to run a request without the intermediary
functioning of :meth:`TestApp.get` etc. For instance, to
test a WebDAV method::
resp = app.request('/new-col', method='MKCOL')
Note that the request won't have a body unless you specify it,
like::
resp = app.request('/test.txt', method='PUT', body='test')
You can use :class:`webtest.TestRequest`::
req = webtest.TestRequest.blank('/url/', method='GET')
resp = app.do_request(req)
"""
if isinstance(url_or_req, str):
url_or_req = str(url_or_req)
for (k, v) in req_params.items():
if isinstance(v, str):
req_params[k] = str(v)
if isinstance(url_or_req, str):
req = self.RequestClass.blank(url_or_req, **req_params)
else:
req = url_or_req.copy()
for name, value in req_params.items():
setattr(req, name, value)
req.environ['paste.throw_errors'] = True
for name, value in self.extra_environ.items():
req.environ.setdefault(name, value)
return self.do_request(req,
status=status,
expect_errors=expect_errors,
)
| (self, url_or_req, status=None, expect_errors=False, **req_params) |
7,949 | webtest.app | reset |
Resets the state of the application; currently just clears
saved cookies.
| def reset(self):
"""
Resets the state of the application; currently just clears
saved cookies.
"""
self.cookiejar.clear()
| (self) |
7,950 | webtest.app | set_authorization | null | def set_authorization(self, value):
self.authorization_value = value
if value is not None:
invalid_value = (
"You should use a value like ('Basic', ('user', 'password'))"
" OR ('Bearer', 'token') OR ('JWT', 'token')"
)
if isinstance(value, (list, tuple)) and len(value) == 2:
authtype, val = value
if authtype == 'Basic' and val and \
isinstance(val, (list, tuple)):
val = ':'.join(list(val))
val = b64encode(to_bytes(val)).strip()
val = val.decode('latin1')
elif authtype in ('Bearer', 'JWT') and val and \
isinstance(val, (str, str)):
val = val.strip()
else:
raise ValueError(invalid_value)
value = str('%s %s' % (authtype, val))
else:
raise ValueError(invalid_value)
self.extra_environ.update({
'HTTP_AUTHORIZATION': value,
})
else:
if 'HTTP_AUTHORIZATION' in self.extra_environ:
del self.extra_environ['HTTP_AUTHORIZATION']
| (self, value) |
7,951 | webtest.app | set_cookie |
Sets a cookie to be passed through with requests.
| def set_cookie(self, name, value):
"""
Sets a cookie to be passed through with requests.
"""
cookie_domain = self.extra_environ.get('HTTP_HOST', '.localhost')
cookie_domain = cookie_domain.split(':', 1)[0]
if '.' not in cookie_domain:
cookie_domain = "%s.local" % cookie_domain
value = escape_cookie_value(value)
cookie = http_cookiejar.Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain=cookie_domain,
domain_specified=True,
domain_initial_dot=False,
path='/',
path_specified=True,
secure=False,
expires=None,
discard=False,
comment=None,
comment_url=None,
rest=None
)
self.cookiejar.set_cookie(cookie)
| (self, name, value) |
7,952 | webtest.app | set_parser_features |
Changes the parser used by BeautifulSoup. See its documentation to
know the supported parsers.
| def set_parser_features(self, parser_features):
"""
Changes the parser used by BeautifulSoup. See its documentation to
know the supported parsers.
"""
self.RequestClass.ResponseClass.parser_features = parser_features
| (self, parser_features) |
7,953 | webtest.app | TestRequest | A subclass of webob.Request | class TestRequest(webob.BaseRequest):
"""A subclass of webob.Request"""
ResponseClass = TestResponse
| (environ, charset=None, unicode_errors=None, decode_param_names=None, **kw) |
7,954 | webob.request | __init__ | null | def __init__(self, environ, charset=None, unicode_errors=None,
decode_param_names=None, **kw):
if type(environ) is not dict:
raise TypeError(
"WSGI environ must be a dict; you passed %r" % (environ,))
if unicode_errors is not None:
warnings.warn(
"You unicode_errors=%r to the Request constructor. Passing a "
"``unicode_errors`` value to the Request is no longer "
"supported in WebOb 1.2+. This value has been ignored " % (
unicode_errors,),
DeprecationWarning
)
if decode_param_names is not None:
warnings.warn(
"You passed decode_param_names=%r to the Request constructor. "
"Passing a ``decode_param_names`` value to the Request "
"is no longer supported in WebOb 1.2+. This value has "
"been ignored " % (decode_param_names,),
DeprecationWarning
)
if not _is_utf8(charset):
raise DeprecationWarning(
"You passed charset=%r to the Request constructor. As of "
"WebOb 1.2, if your application needs a non-UTF-8 request "
"charset, please construct the request without a charset or "
"with a charset of 'None', then use ``req = "
"req.decode(charset)``" % charset
)
d = self.__dict__
d['environ'] = environ
if kw:
cls = self.__class__
if 'method' in kw:
# set method first, because .body setters
# depend on it for checks
self.method = kw.pop('method')
for name, value in kw.items():
if not hasattr(cls, name):
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
| (self, environ, charset=None, unicode_errors=None, decode_param_names=None, **kw) |
7,955 | webob.request | __repr__ | null | def __repr__(self):
try:
name = '%s %s' % (self.method, self.url)
except KeyError:
name = '(invalid WSGI environ)'
msg = '<%s at 0x%x %s>' % (
self.__class__.__name__,
abs(id(self)), name)
return msg
| (self) |
7,956 | webob.request | as_text | null | def as_text(self):
bytes = self.as_bytes()
return bytes.decode(self.charset)
| (self) |
7,957 | webob.request | _cache_control__del | null | def _cache_control__del(self):
env = self.environ
if 'HTTP_CACHE_CONTROL' in env:
del env['HTTP_CACHE_CONTROL']
if 'webob._cache_control' in env:
del env['webob._cache_control']
| (self) |
7,958 | webob.request | _cache_control__get |
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):
"""
Get/set/modify the Cache-Control header (`HTTP spec section 14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)
"""
env = self.environ
value = env.get('HTTP_CACHE_CONTROL', '')
cache_header, cache_obj = env.get('webob._cache_control', (None, None))
if cache_obj is not None and cache_header == value:
return cache_obj
cache_obj = CacheControl.parse(value,
updates_to=self._update_cache_control,
type='request')
env['webob._cache_control'] = (value, cache_obj)
return cache_obj
| (self) |
7,959 | webob.request | _cache_control__set | null | def _cache_control__set(self, value):
env = self.environ
value = value or ''
if isinstance(value, dict):
value = CacheControl(value, type='request')
if isinstance(value, CacheControl):
str_value = str(value)
env['HTTP_CACHE_CONTROL'] = str_value
env['webob._cache_control'] = (str_value, value)
else:
env['HTTP_CACHE_CONTROL'] = str(value)
env['webob._cache_control'] = (None, None)
| (self, value) |
7,960 | webob.request | _check_charset | null | def _check_charset(self):
if self.charset != 'UTF-8':
raise DeprecationWarning(
"Requests are expected to be submitted in UTF-8, not %s. "
"You can fix this by doing req = req.decode('%s')" % (
self.charset, self.charset)
)
| (self) |
7,961 | webob.request | _content_type__get | Return the content type, but leaving off any parameters (like
charset, but also things like the type in ``application/atom+xml;
type=entry``)
If you set this property, you can include parameters, or if
you don't include any parameters in the value then existing
parameters will be preserved.
| def _content_type__get(self):
"""Return the content type, but leaving off any parameters (like
charset, but also things like the type in ``application/atom+xml;
type=entry``)
If you set this property, you can include parameters, or if
you don't include any parameters in the value then existing
parameters will be preserved.
"""
return self._content_type_raw.split(';', 1)[0]
| (self) |
7,962 | webob.request | _content_type__set | null | def _content_type__set(self, value=None):
if value is not None:
value = str(value)
if ';' not in value:
content_type = self._content_type_raw
if ';' in content_type:
value += ';' + content_type.split(';', 1)[1]
self._content_type_raw = value
| (self, value=None) |
7,963 | webob.request | _headers__get |
All the request headers as a case-insensitive dictionary-like
object.
| def _headers__get(self):
"""
All the request headers as a case-insensitive dictionary-like
object.
"""
if self._headers is None:
self._headers = EnvironHeaders(self.environ)
return self._headers
| (self) |
7,964 | webob.request | _headers__set | null | def _headers__set(self, value):
self.headers.clear()
self.headers.update(value)
| (self, value) |
7,965 | webob.request | _host__del | null | def _host__del(self):
if 'HTTP_HOST' in self.environ:
del self.environ['HTTP_HOST']
| (self) |
7,966 | webob.request | _host__get | Host name provided in HTTP_HOST, with fall-back to SERVER_NAME | def _host__get(self):
"""Host name provided in HTTP_HOST, with fall-back to SERVER_NAME"""
if 'HTTP_HOST' in self.environ:
return self.environ['HTTP_HOST']
else:
return '%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ
| (self) |
7,967 | webob.request | _host__set | null | def _host__set(self, value):
self.environ['HTTP_HOST'] = value
| (self, value) |
7,968 | webob.request | _json_body__del | null | def _json_body__del(self):
del self.body
| (self) |
7,969 | webob.request | _json_body__get | Access the body of the request as JSON | def _json_body__get(self):
"""Access the body of the request as JSON"""
return json.loads(self.body.decode(self.charset))
| (self) |
7,970 | webob.request | _json_body__set | null | def _json_body__set(self, value):
self.body = json.dumps(value, separators=(',', ':')).encode(self.charset)
| (self, value) |
7,971 | webob.request | _text__del | null | def _text__del(self):
del self.body
| (self) |
7,972 | webob.request | _text__get |
Get/set the text value of the body
| def _text__get(self):
"""
Get/set the text value of the body
"""
if not self.charset:
raise AttributeError(
"You cannot access Request.text unless charset is set")
body = self.body
return body.decode(self.charset)
| (self) |
7,973 | webob.request | _text__set | null | def _text__set(self, value):
if not self.charset:
raise AttributeError(
"You cannot access Response.text unless charset is set")
if not isinstance(value, text_type):
raise TypeError(
"You can only set Request.text to a unicode string "
"(not %s)" % type(value))
self.body = value.encode(self.charset)
| (self, value) |
7,974 | webob.request | _update_cache_control | null | def _update_cache_control(self, prop_dict):
self.environ['HTTP_CACHE_CONTROL'] = serialize_cache_control(prop_dict)
| (self, prop_dict) |
7,975 | webob.request | _urlargs__del | null | def _urlargs__del(self):
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][1]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
(), self.environ['wsgiorg.routing_args'][1])
| (self) |
7,976 | webob.request | _urlargs__get |
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):
"""
Return any *positional* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][0]
else:
# Since you can't update this value in-place, we don't need
# to set the key in the environment
return ()
| (self) |
7,977 | webob.request | _urlargs__set | null | def _urlargs__set(self, value):
environ = self.environ
if 'paste.urlvars' in environ:
# Some overlap between this and wsgiorg.routing_args; we need
# wsgiorg.routing_args to make this work
routing_args = (value, environ.pop('paste.urlvars'))
elif 'wsgiorg.routing_args' in environ:
routing_args = (value, environ['wsgiorg.routing_args'][1])
else:
routing_args = (value, {})
environ['wsgiorg.routing_args'] = routing_args
| (self, value) |
7,978 | webob.request | _urlvars__del | null | def _urlvars__del(self):
if 'paste.urlvars' in self.environ:
del self.environ['paste.urlvars']
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][0]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
self.environ['wsgiorg.routing_args'][0], {})
| (self) |
7,979 | webob.request | _urlvars__get |
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):
"""
Return any *named* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
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
| (self) |
7,980 | webob.request | _urlvars__set | null | def _urlvars__set(self, value):
environ = self.environ
if 'wsgiorg.routing_args' in environ:
environ['wsgiorg.routing_args'] = (
environ['wsgiorg.routing_args'][0], value)
if 'paste.urlvars' in environ:
del environ['paste.urlvars']
elif 'paste.urlvars' in environ:
environ['paste.urlvars'] = value
else:
environ['wsgiorg.routing_args'] = ((), value)
| (self, value) |
7,981 | webob.request | as_bytes |
Return HTTP bytes representing this request.
If skip_body is True, exclude the body.
If skip_body is an integer larger than one, skip body
only if its length is bigger than that number.
| def as_bytes(self, skip_body=False):
"""
Return HTTP bytes representing this request.
If skip_body is True, exclude the body.
If skip_body is an integer larger than one, skip body
only if its length is bigger than that number.
"""
url = self.url
host = self.host_url
assert url.startswith(host)
url = url[len(host):]
parts = [bytes_('%s %s %s' % (self.method, url, self.http_version))]
# acquire body before we handle headers so that
# content-length will be set
body = None
if self.is_body_readable:
if skip_body > 1:
if len(self.body) > skip_body:
body = bytes_('<body skipped (len=%s)>' % len(self.body))
else:
skip_body = False
if not skip_body:
body = self.body
for k, v in sorted(self.headers.items()):
header = bytes_('%s: %s' % (k, v))
parts.append(header)
if body:
parts.extend([b'', body])
# HTTP clearly specifies CRLF
return b'\r\n'.join(parts)
| (self, skip_body=False) |
7,983 | webob.request | call_application |
Call the given WSGI application, returning ``(status_string,
headerlist, app_iter)``
Be sure to call ``app_iter.close()`` if it's there.
If catch_exc_info is true, then returns ``(status_string,
headerlist, app_iter, exc_info)``, where the fourth item may
be None, but won't be if there was an exception. If you don't
do this and there was an exception, the exception will be
raised directly.
| def call_application(self, application, catch_exc_info=False):
"""
Call the given WSGI application, returning ``(status_string,
headerlist, app_iter)``
Be sure to call ``app_iter.close()`` if it's there.
If catch_exc_info is true, then returns ``(status_string,
headerlist, app_iter, exc_info)``, where the fourth item may
be None, but won't be if there was an exception. If you don't
do this and there was an exception, the exception will be
raised directly.
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
captured = []
output = []
def start_response(status, headers, exc_info=None):
if exc_info is not None and not catch_exc_info:
reraise(exc_info)
captured[:] = [status, headers, exc_info]
return output.append
app_iter = application(self.environ, start_response)
if output or not captured:
try:
output.extend(app_iter)
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
app_iter = output
if catch_exc_info:
return (captured[0], captured[1], app_iter, captured[2])
else:
return (captured[0], captured[1], app_iter)
| (self, application, catch_exc_info=False) |
7,984 | webob.request | copy |
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
| def copy(self):
"""
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
"""
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env)
new_req.copy_body()
return new_req
| (self) |
7,985 | webob.request | copy_body |
Copies the body, in cases where it might be shared with another request
object and that is not desired.
This copies the body either into a BytesIO object (through setting
req.body) or a temporary file.
| def copy_body(self):
"""
Copies the body, in cases where it might be shared with another request
object and that is not desired.
This copies the body either into a BytesIO object (through setting
req.body) or a temporary file.
"""
if self.is_body_readable:
# Before we copy, if we can, rewind the body file
if self.is_body_seekable:
self.body_file_raw.seek(0)
tempfile_limit = self.request_body_tempfile_limit
todo = self.content_length if self.content_length is not None else 65535
newbody = b''
fileobj = None
input = self.body_file
while todo > 0:
data = input.read(min(todo, 65535))
if not data and self.content_length is None:
# We attempted to read more data, but got none, break.
# This can happen if for instance we are reading as much as
# we can because we don't have a Content-Length...
break
elif not data:
# We have a Content-Length and we attempted to read, but
# there was nothing more to read. Oh the humanity! This
# should rarely if never happen because self.body_file
# should be a LimitedLengthFile which should already have
# raised if there was less data than expected.
raise DisconnectionError(
"Client disconnected (%s more bytes were expected)" % todo
)
if fileobj:
fileobj.write(data)
else:
newbody += data
# When we have enough data that we need a tempfile, let's
# create one, then clear the temporary variable we were
# using
if len(newbody) > tempfile_limit:
fileobj = self.make_tempfile()
fileobj.write(newbody)
newbody = b''
# Only decrement todo if Content-Length is set
if self.content_length is not None:
todo -= len(data)
if fileobj:
# We apparently had enough data to need a file
# Set the Content-Length to the amount of data that was just
# written.
self.content_length = fileobj.tell()
# Seek it back to the beginning
fileobj.seek(0)
self.body_file_raw = fileobj
# Allow it to be seeked in the future, so we don't need to copy
# for things like .body
self.is_body_seekable = True
# Not strictly required since Content-Length is set
self.is_body_readable = True
else:
# No file created, set the body and let it deal with creating
# Content-Length and other vars.
self.body = newbody
else:
# Always leave the request with a valid body, and this is pretty
# cheap.
self.body = b''
| (self) |
7,986 | webob.request | copy_get |
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):
"""
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.
"""
env = self.environ.copy()
return self.__class__(env, method='GET', content_type=None,
body=b'')
| (self) |
7,987 | webob.request | decode | null | def decode(self, charset=None, errors='strict'):
charset = charset or self.charset
if charset == 'UTF-8':
return self
# cookies and path are always utf-8
t = Transcoder(charset, errors)
new_content_type = CHARSET_RE.sub('; charset="UTF-8"',
self._content_type_raw)
content_type = self.content_type
r = self.__class__(
self.environ.copy(),
query_string=t.transcode_query(self.query_string),
content_type=new_content_type,
)
if content_type == 'application/x-www-form-urlencoded':
r.body = bytes_(t.transcode_query(native_(self.body)))
return r
elif content_type != 'multipart/form-data':
return r
fs_environ = self.environ.copy()
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
if PY2:
fs = cgi_FieldStorage(fp=self.body_file,
environ=fs_environ,
keep_blank_values=True)
else:
fs = cgi_FieldStorage(fp=self.body_file,
environ=fs_environ,
keep_blank_values=True,
encoding=charset,
errors=errors)
fout = t.transcode_fs(fs, r._content_type_raw)
# this order is important, because setting body_file
# resets content_length
r.body_file = fout
r.content_length = fout.tell()
fout.seek(0)
return r
| (self, charset=None, errors='strict') |
7,988 | webob.request | encget | null | def encget(self, key, default=NoDefault, encattr=None):
val = self.environ.get(key, default)
if val is NoDefault:
raise KeyError(key)
if val is default:
return default
if not encattr:
return val
encoding = getattr(self, encattr)
if PY2:
return val.decode(encoding)
if encoding in _LATIN_ENCODINGS: # shortcut
return val
return bytes_(val, 'latin-1').decode(encoding)
| (self, key, default=(No Default), encattr=None) |
7,989 | webob.request | encset | null | def encset(self, key, val, encattr=None):
if encattr:
encoding = getattr(self, encattr)
else:
encoding = 'ascii'
if PY2: # pragma: no cover
self.environ[key] = bytes_(val, encoding)
else:
self.environ[key] = bytes_(val, encoding).decode('latin-1')
| (self, key, val, encattr=None) |
7,990 | webob.request | send |
Like ``.call_application(application)``, except returns a
response object with ``.status``, ``.headers``, and ``.body``
attributes.
This will use ``self.ResponseClass`` to figure out the class
of the response object to return.
If ``application`` is not given, this will send the request to
``self.make_default_send_app()``
| def send(self, application=None, catch_exc_info=False):
"""
Like ``.call_application(application)``, except returns a
response object with ``.status``, ``.headers``, and ``.body``
attributes.
This will use ``self.ResponseClass`` to figure out the class
of the response object to return.
If ``application`` is not given, this will send the request to
``self.make_default_send_app()``
"""
if application is None:
application = self.make_default_send_app()
if catch_exc_info:
status, headers, app_iter, exc_info = self.call_application(
application, catch_exc_info=True)
del exc_info
else:
status, headers, app_iter = self.call_application(
application, catch_exc_info=False)
return self.ResponseClass(
status=status, headerlist=list(headers), app_iter=app_iter)
| (self, application=None, catch_exc_info=False) |
7,991 | webob.request | make_body_seekable |
This forces ``environ['wsgi.input']`` to be seekable.
That means that, the content is copied into a BytesIO or temporary
file and flagged as seekable, so that it will not be unnecessarily
copied again.
After calling this method the .body_file is always seeked to the
start of file and .content_length is not None.
The choice to copy to BytesIO is made from
``self.request_body_tempfile_limit``
| def make_body_seekable(self):
"""
This forces ``environ['wsgi.input']`` to be seekable.
That means that, the content is copied into a BytesIO or temporary
file and flagged as seekable, so that it will not be unnecessarily
copied again.
After calling this method the .body_file is always seeked to the
start of file and .content_length is not None.
The choice to copy to BytesIO is made from
``self.request_body_tempfile_limit``
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
else:
self.copy_body()
| (self) |
7,992 | webob.request | make_default_send_app | null | def make_default_send_app(self):
global _client
try:
client = _client
except NameError:
from webob import client
_client = client
return client.send_request_app
| (self) |
7,993 | webob.request | make_tempfile |
Create a tempfile to store big request body.
This API is not stable yet. A 'size' argument might be added.
| def make_tempfile(self):
"""
Create a tempfile to store big request body.
This API is not stable yet. A 'size' argument might be added.
"""
return tempfile.TemporaryFile()
| (self) |
7,994 | webob.request | path_info_peek |
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):
"""
Returns the next segment on PATH_INFO, or None if there is no
next segment. Doesn't modify the environment.
"""
path = self.path_info
if not path:
return None
path = path.lstrip('/')
return path.split('/', 1)[0]
| (self) |
7,995 | webob.request | path_info_pop |
'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.
Optional ``pattern`` argument is a regexp to match the return value
before returning. If there is no match, no changes are made to the
request and None is returned.
| def path_info_pop(self, pattern=None):
"""
'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.
Optional ``pattern`` argument is a regexp to match the return value
before returning. If there is no match, no changes are made to the
request and None is returned.
"""
path = self.path_info
if not path:
return None
slashes = ''
while path.startswith('/'):
slashes += '/'
path = path[1:]
idx = path.find('/')
if idx == -1:
idx = len(path)
r = path[:idx]
if pattern is None or re.match(pattern, r):
self.script_name += slashes + r
self.path_info = path[idx:]
return r
| (self, pattern=None) |
7,996 | webob.request | relative_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):
"""
Resolve other_url relative to the request URL.
If ``to_application`` is True, then resolve it relative to the
URL with only SCRIPT_NAME
"""
if to_application:
url = self.application_url
if not url.endswith('/'):
url += '/'
else:
url = self.path_url
return urlparse.urljoin(url, other_url)
| (self, other_url, to_application=False) |
7,997 | webob.request | remove_conditional_headers |
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,
remove_range=True,
remove_match=True,
remove_modified=True):
"""
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.
"""
check_keys = []
if remove_range:
check_keys += ['HTTP_IF_RANGE', 'HTTP_RANGE']
if remove_match:
check_keys.append('HTTP_IF_NONE_MATCH')
if remove_modified:
check_keys.append('HTTP_IF_MODIFIED_SINCE')
if remove_encoding:
check_keys.append('HTTP_ACCEPT_ENCODING')
for key in check_keys:
if key in self.environ:
del self.environ[key]
| (self, remove_encoding=True, remove_range=True, remove_match=True, remove_modified=True) |
7,999 | webtest.response | TestResponse |
Instances of this class are returned by
:class:`~webtest.app.TestApp` methods.
| class TestResponse(webob.Response):
"""
Instances of this class are returned by
:class:`~webtest.app.TestApp` methods.
"""
request = None
_forms_indexed = None
parser_features = 'html.parser'
@property
def forms(self):
"""
Returns a dictionary containing all the forms in the pages as
:class:`~webtest.forms.Form` objects. Indexes are both in
order (from zero) and by form id (if the form is given an id).
See :doc:`forms` for more info on form objects.
"""
if self._forms_indexed is None:
self._parse_forms()
return self._forms_indexed
@property
def form(self):
"""
If there is only one form on the page, return it as a
:class:`~webtest.forms.Form` object; raise a TypeError is
there are no form or multiple forms.
"""
forms_ = self.forms
if not forms_:
raise TypeError(
"You used response.form, but no forms exist")
if 1 in forms_:
# There is more than one form
raise TypeError(
"You used response.form, but more than one form exists")
return forms_[0]
@property
def testbody(self):
self.decode_content()
if self.charset:
try:
return self.text
except UnicodeDecodeError:
return self.body.decode(self.charset, 'replace')
return self.body.decode('ascii', 'replace')
_tag_re = re.compile(r'<(/?)([:a-z0-9_\-]*)(.*?)>', re.S | re.I)
def _parse_forms(self):
forms_ = self._forms_indexed = {}
form_texts = [str(f) for f in self.html('form')]
for i, text in enumerate(form_texts):
form = forms.Form(self, text, self.parser_features)
forms_[i] = form
if form.id:
forms_[form.id] = form
def _follow(self, **kw):
location = self.headers['location']
abslocation = urlparse.urljoin(self.request.url, location)
# @@: We should test that it's not a remote redirect
return self.test_app.get(abslocation, **kw)
def follow(self, **kw):
"""
If this response is a redirect, follow that redirect. It is an
error if it is not a redirect response. Any keyword
arguments are passed to :class:`webtest.app.TestApp.get`. Returns
another :class:`TestResponse` object.
"""
if not (300 <= self.status_int < 400):
raise AssertionError(
"You can only follow redirect responses (not %s)" % self.status
)
return self._follow(**kw)
def maybe_follow(self, **kw):
"""
Follow all redirects. If this response is not a redirect, do nothing.
Any keyword arguments are passed to :class:`webtest.app.TestApp.get`.
Returns another :class:`TestResponse` object.
"""
remaining_redirects = 100 # infinite loops protection
response = self
while 300 <= response.status_int < 400 and remaining_redirects:
response = response._follow(**kw)
remaining_redirects -= 1
if remaining_redirects <= 0:
raise AssertionError("redirects chain looks infinite")
return response
def click(self, description=None, linkid=None, href=None,
index=None, verbose=False,
extra_environ=None):
"""
Click the link as described. Each of ``description``,
``linkid``, and ``url`` are *patterns*, meaning that they are
either strings (regular expressions), compiled regular
expressions (objects with a ``search`` method), or callables
returning true or false.
All the given patterns are ANDed together:
* ``description`` is a pattern that matches the contents of the
anchor (HTML and all -- everything between ``<a...>`` and
``</a>``)
* ``linkid`` is a pattern that matches the ``id`` attribute of
the anchor. It will receive the empty string if no id is
given.
* ``href`` is a pattern that matches the ``href`` of the anchor;
the literal content of that attribute, not the fully qualified
attribute.
If more than one link matches, then the ``index`` link is
followed. If ``index`` is not given and more than one link
matches, or if no link matches, then ``IndexError`` will be
raised.
If you give ``verbose`` then messages will be printed about
each link, and why it does or doesn't match. If you use
``app.click(verbose=True)`` you'll see a list of all the
links.
You can use multiple criteria to essentially assert multiple
aspects about the link, e.g., where the link's destination is.
"""
found_html, found_desc, found_attrs = self._find_element(
tag='a', href_attr='href',
href_extract=None,
content=description,
id=linkid,
href_pattern=href,
index=index, verbose=verbose)
extra_environ = extra_environ or {}
extra_environ.setdefault('HTTP_REFERER', str(self.request.url))
return self.goto(str(found_attrs['uri']), extra_environ=extra_environ)
def clickbutton(self, description=None, buttonid=None, href=None,
index=None, verbose=False):
"""
Like :meth:`~webtest.response.TestResponse.click`, except looks
for link-like buttons.
This kind of button should look like
``<button onclick="...location.href='url'...">``.
"""
found_html, found_desc, found_attrs = self._find_element(
tag='button', href_attr='onclick',
href_extract=re.compile(r"location\.href='(.*?)'"),
content=description,
id=buttonid,
href_pattern=href,
index=index, verbose=verbose)
extra_environ = {'HTTP_REFERER': str(self.request.url)}
return self.goto(str(found_attrs['uri']), extra_environ=extra_environ)
def _find_element(self, tag, href_attr, href_extract,
content, id,
href_pattern,
index, verbose):
content_pat = utils.make_pattern(content)
id_pat = utils.make_pattern(id)
href_pat = utils.make_pattern(href_pattern)
def printlog(s):
if verbose:
print(s)
found_links = []
total_links = 0
for element in self.html.find_all(tag):
el_html = str(element)
el_content = element.decode_contents()
attrs = element
if verbose:
printlog('Element: %r' % el_html)
if not attrs.get(href_attr):
printlog(' Skipped: no %s attribute' % href_attr)
continue
el_href = attrs[href_attr]
if href_extract:
m = href_extract.search(el_href)
if not m:
printlog(" Skipped: doesn't match extract pattern")
continue
el_href = m.group(1)
attrs['uri'] = el_href
if el_href.startswith('#'):
printlog(' Skipped: only internal fragment href')
continue
if el_href.startswith('javascript:'):
printlog(' Skipped: cannot follow javascript:')
continue
total_links += 1
if content_pat and not content_pat(el_content):
printlog(" Skipped: doesn't match description")
continue
if id_pat and not id_pat(attrs.get('id', '')):
printlog(" Skipped: doesn't match id")
continue
if href_pat and not href_pat(el_href):
printlog(" Skipped: doesn't match href")
continue
printlog(" Accepted")
found_links.append((el_html, el_content, attrs))
if not found_links:
raise IndexError(
"No matching elements found (from %s possible)"
% total_links)
if index is None:
if len(found_links) > 1:
raise IndexError(
"Multiple links match: %s"
% ', '.join([repr(anc) for anc, d, attr in found_links]))
found_link = found_links[0]
else:
try:
found_link = found_links[index]
except IndexError:
raise IndexError(
"Only %s (out of %s) links match; index %s out of range"
% (len(found_links), total_links, index))
return found_link
def goto(self, href, method='get', **args):
"""
Go to the (potentially relative) link ``href``, using the
given method (``'get'`` or ``'post'``) and any extra arguments
you want to pass to the :meth:`webtest.app.TestApp.get` or
:meth:`webtest.app.TestApp.post` methods.
All hostnames and schemes will be ignored.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(href)
# We
scheme = host = fragment = ''
href = urlparse.urlunsplit((scheme, host, path, query, fragment))
href = urlparse.urljoin(self.request.url, href)
method = method.lower()
assert method in ('get', 'post'), (
'Only "get" or "post" are allowed for method (you gave %r)'
% method)
if method == 'get':
method = self.test_app.get
else:
method = self.test_app.post
return method(href, **args)
_normal_body_regex = re.compile(to_bytes(r'[ \n\r\t]+'))
@property
def normal_body(self):
"""
Return the whitespace-normalized body
"""
if getattr(self, '_normal_body', None) is None:
self._normal_body = self._normal_body_regex.sub(b' ', self.body)
return self._normal_body
_unicode_normal_body_regex = re.compile('[ \\n\\r\\t]+')
@property
def unicode_normal_body(self):
"""
Return the whitespace-normalized body, as unicode
"""
if not self.charset:
raise AttributeError(
"You cannot access Response.unicode_normal_body "
"unless charset is set")
if getattr(self, '_unicode_normal_body', None) is None:
self._unicode_normal_body = self._unicode_normal_body_regex.sub(
' ', self.testbody)
return self._unicode_normal_body
def __contains__(self, s):
"""
A response 'contains' a string if it is present in the body
of the response. Whitespace is normalized when searching
for a string.
"""
if not self.charset and isinstance(s, str):
s = s.encode('utf8')
if isinstance(s, bytes):
return s in self.body or s in self.normal_body
return s in self.testbody or s in self.unicode_normal_body
def mustcontain(self, *strings, **kw):
"""mustcontain(*strings, no=[])
Assert that the response contains all of the strings passed
in as arguments.
Equivalent to::
assert string in res
Can take a `no` keyword argument that can be a string or a
list of strings which must not be present in the response.
"""
if 'no' in kw:
no = kw['no']
del kw['no']
if isinstance(no, str):
no = [no]
else:
no = []
if kw:
raise TypeError(
"The only keyword argument allowed is 'no'")
for s in strings:
if s not in self:
print_stderr("Actual response (no %r):" % s)
print_stderr(str(self))
raise IndexError(
"Body does not contain string %r" % s)
for no_s in no:
if no_s in self:
print_stderr("Actual response (has %r)" % no_s)
print_stderr(str(self))
raise IndexError(
"Body contains bad string %r" % no_s)
def __str__(self):
simple_body = '\n'.join([l for l in self.testbody.splitlines()
if l.strip()])
headers = [(n.title(), v)
for n, v in self.headerlist
if n.lower() != 'content-length']
headers.sort()
output = 'Response: %s\n%s\n%s' % (
self.status,
'\n'.join(['%s: %s' % (n, v) for n, v in headers]),
simple_body)
return output
def __unicode__(self):
output = str(self)
return output
def __repr__(self):
# Specifically intended for doctests
if self.content_type:
ct = ' %s' % self.content_type
else:
ct = ''
if self.body:
br = repr(self.body)
if len(br) > 18:
br = br[:10] + '...' + br[-5:]
br += '/%s' % len(self.body)
body = ' body=%s' % br
else:
body = ' no body'
if self.location:
location = ' location: %s' % self.location
else:
location = ''
return ('<' + self.status + ct + location + body + '>')
@property
def html(self):
"""
Returns the response as a `BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html>`_
object.
Only works with HTML responses; other content-types raise
AttributeError.
"""
if 'html' not in self.content_type:
raise AttributeError(
"Not an HTML response body (content-type: %s)"
% self.content_type)
soup = BeautifulSoup(self.testbody, self.parser_features)
return soup
@property
def xml(self):
"""
Returns the response as an :mod:`ElementTree
<python:xml.etree.ElementTree>` object.
Only works with XML responses; other content-types raise
AttributeError
"""
if 'xml' not in self.content_type:
raise AttributeError(
"Not an XML response body (content-type: %s)"
% self.content_type)
try:
from xml.etree import ElementTree
except ImportError: # pragma: no cover
try:
import ElementTree
except ImportError:
try:
from elementtree import ElementTree # NOQA
except ImportError:
raise ImportError(
"You must have ElementTree installed "
"(or use Python 2.5) to use response.xml")
# ElementTree can't parse unicode => use `body` instead of `testbody`
return ElementTree.XML(self.body)
@property
def lxml(self):
"""
Returns the response as an `lxml object <https://lxml.de/>`_.
You must have lxml installed to use this.
If this is an HTML response and you have lxml 2.x installed,
then an ``lxml.html.HTML`` object will be returned; if you
have an earlier version of lxml then a ``lxml.HTML`` object
will be returned.
"""
if 'html' not in self.content_type and \
'xml' not in self.content_type:
raise AttributeError(
"Not an XML or HTML response body (content-type: %s)"
% self.content_type)
try:
from lxml import etree
except ImportError: # pragma: no cover
raise ImportError(
"You must have lxml installed to use response.lxml")
try:
from lxml.html import fromstring
except ImportError: # pragma: no cover
fromstring = etree.HTML
# FIXME: would be nice to set xml:base, in some fashion
if self.content_type == 'text/html':
return fromstring(self.testbody, base_url=self.request.url)
else:
return etree.XML(self.testbody, base_url=self.request.url)
@property
def json(self):
"""
Return the response as a JSON response.
The content type must be one of json type to use this.
"""
if not self.content_type.endswith(('+json', '/json')):
raise AttributeError(
"Not a JSON response body (content-type: %s)"
% self.content_type)
return self.json_body
@property
def pyquery(self):
"""
Returns the response as a `PyQuery
<https://pypi.org/project/pyquery/>`_ object.
Only works with HTML and XML responses; other content-types raise
AttributeError.
"""
if 'html' not in self.content_type and 'xml' not in self.content_type:
raise AttributeError(
"Not an HTML or XML response body (content-type: %s)"
% self.content_type)
try:
from pyquery import PyQuery
except ImportError: # pragma: no cover
raise ImportError(
"You must have PyQuery installed to use response.pyquery")
d = PyQuery(self.testbody)
return d
def showbrowser(self):
"""
Show this response in a browser window (for debugging purposes,
when it's hard to read the HTML).
"""
import webbrowser
import tempfile
f = tempfile.NamedTemporaryFile(prefix='webtest-page',
suffix='.html')
name = f.name
f.close()
f = open(name, 'w')
f.write(self.body.decode(self.charset or 'ascii', 'replace'))
f.close()
if name[0] != '/': # pragma: no cover
# windows ...
url = 'file:///' + name
else:
url = 'file://' + name
webbrowser.open_new(url)
| (body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, charset=<object object at 0x7f84425d2070>, **kw) |
8,000 | webob.response | __call__ |
WSGI application interface
| def __call__(self, environ, start_response):
"""
WSGI application interface
"""
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':
# Special case here...
return EmptyResponse(self._app_iter)
return self._app_iter
| (self, environ, start_response) |
8,001 | webtest.response | __contains__ |
A response 'contains' a string if it is present in the body
of the response. Whitespace is normalized when searching
for a string.
| def __contains__(self, s):
"""
A response 'contains' a string if it is present in the body
of the response. Whitespace is normalized when searching
for a string.
"""
if not self.charset and isinstance(s, str):
s = s.encode('utf8')
if isinstance(s, bytes):
return s in self.body or s in self.normal_body
return s in self.testbody or s in self.unicode_normal_body
| (self, s) |
8,002 | webob.response | __init__ | null | def __init__(self, body=None, status=None, headerlist=None, app_iter=None,
content_type=None, conditional_response=None, charset=_marker,
**kw):
# Do some sanity checking, and turn json_body into an actual body
if app_iter is None and body is None and ('json_body' in kw or 'json' in kw):
if 'json_body' in kw:
json_body = kw.pop('json_body')
else:
json_body = kw.pop('json')
body = json.dumps(json_body, separators=(',', ':')).encode('UTF-8')
if content_type is None:
content_type = 'application/json'
if app_iter is None:
if body is None:
body = b''
elif body is not None:
raise TypeError(
"You may only give one of the body and app_iter arguments")
# Set up Response.status
if status is None:
self._status = '200 OK'
else:
self.status = status
# Initialize headers
self._headers = None
if headerlist is None:
self._headerlist = []
else:
self._headerlist = headerlist
# Set the encoding for the Response to charset, so if a charset is
# passed but the Content-Type does not allow for a charset, we can
# still encode text_type body's.
# r = Response(
# content_type='application/foo',
# charset='UTF-8',
# body=u'somebody')
# Should work without issues, and the header will be correctly set to
# Content-Type: application/foo with no charset on it.
encoding = None
if charset is not _marker:
encoding = charset
# Does the status code have a body or not?
code_has_body = (
self._status[0] != '1' and
self._status[:3] not in ('204', '205', '304')
)
# We only set the content_type to the one passed to the constructor or
# the default content type if there is none that exists AND there was
# no headerlist passed. If a headerlist was provided then most likely
# the ommission of the Content-Type is on purpose and we shouldn't try
# to be smart about it.
#
# Also allow creation of a empty Response with just the status set to a
# Response with empty body, such as Response(status='204 No Content')
# without the default content_type being set (since empty bodies have
# no Content-Type)
#
# Check if content_type is set because default_content_type could be
# None, in which case there is no content_type, and thus we don't need
# to anything
content_type = content_type or self.default_content_type
if headerlist is None and code_has_body and content_type:
# Set up the charset, if the content_type doesn't already have one
has_charset = 'charset=' in content_type
# If the Content-Type already has a charset, we don't set the user
# provided charset on the Content-Type, so we shouldn't use it as
# the encoding for text_type based body's.
if has_charset:
encoding = None
# Do not use the default_charset for the encoding because we
# want things like
# Response(content_type='image/jpeg',body=u'foo') to raise when
# trying to encode the body.
new_charset = encoding
if (
not has_charset and
charset is _marker and
self.default_charset
):
new_charset = self.default_charset
# Optimize for the default_content_type as shipped by
# WebOb, becuase we know that 'text/html' has a charset,
# otherwise add a charset if the content_type has a charset.
#
# Even if the user supplied charset explicitly, we do not add
# it to the Content-Type unless it has has a charset, instead
# the user supplied charset is solely used for encoding the
# body if it is a text_type
if (
new_charset and
(
content_type == 'text/html' or
_content_type_has_charset(content_type)
)
):
content_type += '; charset=' + new_charset
self._headerlist.append(('Content-Type', content_type))
# Set up conditional response
if conditional_response is None:
self.conditional_response = self.default_conditional_response
else:
self.conditional_response = bool(conditional_response)
# Set up app_iter if the HTTP Status code has a body
if app_iter is None and code_has_body:
if isinstance(body, text_type):
# Fall back to trying self.charset if encoding is not set. In
# most cases encoding will be set to the default value.
encoding = encoding or self.charset
if encoding is None:
raise TypeError(
"You cannot set the body to a text value without a "
"charset")
body = body.encode(encoding)
app_iter = [body]
if headerlist is not None:
self._headerlist[:] = [
(k, v)
for (k, v)
in self._headerlist
if k.lower() != 'content-length'
]
self._headerlist.append(('Content-Length', str(len(body))))
elif app_iter is None and not code_has_body:
app_iter = [b'']
self._app_iter = app_iter
# Loop through all the remaining keyword arguments
for name, value in kw.items():
if not hasattr(self.__class__, name):
# Not a basic attribute
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
| (self, body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, charset=<object object at 0x7f84425d2070>, **kw) |
8,003 | webtest.response | __repr__ | null | def __repr__(self):
# Specifically intended for doctests
if self.content_type:
ct = ' %s' % self.content_type
else:
ct = ''
if self.body:
br = repr(self.body)
if len(br) > 18:
br = br[:10] + '...' + br[-5:]
br += '/%s' % len(self.body)
body = ' body=%s' % br
else:
body = ' no body'
if self.location:
location = ' location: %s' % self.location
else:
location = ''
return ('<' + self.status + ct + location + body + '>')
| (self) |
8,004 | webtest.response | __str__ | null | def __str__(self):
simple_body = '\n'.join([l for l in self.testbody.splitlines()
if l.strip()])
headers = [(n.title(), v)
for n, v in self.headerlist
if n.lower() != 'content-length']
headers.sort()
output = 'Response: %s\n%s\n%s' % (
self.status,
'\n'.join(['%s: %s' % (n, v) for n, v in headers]),
simple_body)
return output
| (self) |
8,005 | webtest.response | __unicode__ | null | def __unicode__(self):
output = str(self)
return output
| (self) |
8,006 | webob.response | _abs_headerlist | null | def _abs_headerlist(self, environ):
# Build the headerlist, if we have a Location header, make it absolute
return [
(k, v) if k.lower() != 'location'
else (k, self._make_location_absolute(environ, v))
for (k, v)
in self._headerlist
]
| (self, environ) |
8,007 | webob.response | _app_iter__del | null | def _app_iter__del(self):
self._app_iter = []
self.content_length = None
| (self) |
8,008 | webob.response | _app_iter__get |
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):
"""
Returns the ``app_iter`` of the response.
If ``body`` was set, this will create an ``app_iter`` from that
``body`` (a single-item list).
"""
return self._app_iter
| (self) |
8,009 | webob.response | _app_iter__set | null | def _app_iter__set(self, value):
if self._app_iter is not None:
# Undo the automatically-set content-length
self.content_length = None
self._app_iter = value
| (self, value) |
8,010 | webob.response | _body__get |
The body of the response, as a :class:`bytes`. This will read in
the entire app_iter if necessary.
| def _body__get(self):
"""
The body of the response, as a :class:`bytes`. This will read in
the entire app_iter if necessary.
"""
app_iter = self._app_iter
# try:
# if len(app_iter) == 1:
# return app_iter[0]
# except:
# pass
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 = b''.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:
# if body-length is zero, we assume it's a HEAD response and
# leave content_length alone
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
| (self) |
8,011 | webob.response | _body__set | null | def _body__set(self, value=b''):
if not isinstance(value, bytes):
if isinstance(value, text_type):
msg = ("You cannot set Response.body to a text object "
"(use Response.text)")
else:
msg = ("You can only set the body to a binary type (not %s)" %
type(value))
raise TypeError(msg)
if self._app_iter is not None:
self.content_md5 = None
self._app_iter = [value]
self.content_length = len(value)
| (self, value=b'') |
8,012 | webob.response | _body_file__del | null | def _body_file__del(self):
del self.body
| (self) |
8,013 | webob.response | _body_file__get |
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):
"""
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.
"""
return ResponseBodyFile(self)
| (self) |
8,014 | webob.response | _body_file__set | null | def _body_file__set(self, file):
self.app_iter = iter_file(file)
| (self, file) |
8,015 | webob.response | _cache_control__del | null | def _cache_control__del(self):
self.cache_control = {}
| (self) |
8,016 | webob.response | _cache_control__get |
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):
"""
Get/set/modify the Cache-Control header (`HTTP spec section 14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_).
"""
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
| (self) |
8,017 | webob.response | _cache_control__set | null | def _cache_control__set(self, value):
# This actually becomes a copy
if not value:
value = ""
if isinstance(value, dict):
value = CacheControl(value, 'response')
if isinstance(value, text_type):
value = str(value)
if isinstance(value, str):
if self._cache_control_obj is None:
self.headers['Cache-Control'] = value
return
value = CacheControl.parse(value, 'response')
cache = self.cache_control
cache.properties.clear()
cache.properties.update(value.properties)
| (self, value) |
8,018 | webob.response | _cache_expires |
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``).
| def _cache_expires(self, seconds=0, **kw):
"""
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``).
"""
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:
# To really expire something, you have to force a
# bunch of these cache control attributes, and IE may
# not pay attention to those still so we also set
# Expires.
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)
| (self, seconds=0, **kw) |
8,019 | webob.response | _charset__del | null | def _charset__del(self):
header = self.headers.pop('Content-Type', None)
if header is None:
# Don't need to remove anything
return
match = CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
self.headers['Content-Type'] = header
| (self) |
8,020 | webob.response | _charset__get |
Get/set the ``charset`` specified in ``Content-Type``.
There is no checking to validate that a ``content_type`` actually
allows for a ``charset`` parameter.
| def _charset__get(self):
"""
Get/set the ``charset`` specified in ``Content-Type``.
There is no checking to validate that a ``content_type`` actually
allows for a ``charset`` parameter.
"""
header = self.headers.get('Content-Type')
if not header:
return None
match = CHARSET_RE.search(header)
if match:
return match.group(1)
return None
| (self) |
8,021 | webob.response | _charset__set | null | def _charset__set(self, charset):
if charset is None:
self._charset__del()
return
header = self.headers.get('Content-Type', None)
if header is None:
raise AttributeError("You cannot set the charset when no "
"content-type is defined")
match = CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
header += '; charset=%s' % charset
self.headers['Content-Type'] = header
| (self, charset) |
8,022 | webob.response | _content_type__del | null | def _content_type__del(self):
self.headers.pop('Content-Type', None)
| (self) |
8,023 | webob.response | _content_type__get |
Get/set the ``Content-Type`` header. If no ``Content-Type`` header is
set, this will return ``None``.
.. versionchanged:: 1.7
Setting a new ``Content-Type`` will remove all ``Content-Type``
parameters and reset the ``charset`` to the default if the
``Content-Type`` is ``text/*`` or XML (``application/xml`` or
``*/*+xml``).
To preserve all ``Content-Type`` parameters, you may use the
following code:
.. code-block:: python
resp = Response()
params = resp.content_type_params
resp.content_type = 'application/something'
resp.content_type_params = params
| def _content_type__get(self):
"""
Get/set the ``Content-Type`` header. If no ``Content-Type`` header is
set, this will return ``None``.
.. versionchanged:: 1.7
Setting a new ``Content-Type`` will remove all ``Content-Type``
parameters and reset the ``charset`` to the default if the
``Content-Type`` is ``text/*`` or XML (``application/xml`` or
``*/*+xml``).
To preserve all ``Content-Type`` parameters, you may use the
following code:
.. code-block:: python
resp = Response()
params = resp.content_type_params
resp.content_type = 'application/something'
resp.content_type_params = params
"""
header = self.headers.get('Content-Type')
if not header:
return None
return header.split(';', 1)[0]
| (self) |
8,024 | webob.response | _content_type__set | null | def _content_type__set(self, value):
if not value:
self._content_type__del()
return
else:
if PY2 and isinstance(value, text_type):
value = value.encode("latin-1")
if not isinstance(value, string_types):
raise TypeError("content_type requires value to be of string_types")
content_type = value
# Set up the charset if the content-type doesn't have one
has_charset = 'charset=' in content_type
new_charset = None
if (
not has_charset and
self.default_charset
):
new_charset = self.default_charset
# Optimize for the default_content_type as shipped by
# WebOb, becuase we know that 'text/html' has a charset,
# otherwise add a charset if the content_type has a charset.
#
# We add the default charset if the content-type is "texty".
if (
new_charset and
(
content_type == 'text/html' or
_content_type_has_charset(content_type)
)
):
content_type += '; charset=' + new_charset
self.headers['Content-Type'] = content_type
| (self, value) |
8,025 | webob.response | _content_type_params__del | null | def _content_type_params__del(self):
self.headers['Content-Type'] = self.headers.get(
'Content-Type', '').split(';', 1)[0]
| (self) |
8,026 | webob.response | _content_type_params__get |
A dictionary of all the parameters in the content type.
(This is not a view, set to change, modifications of the dict will not
be applied otherwise.)
| def _content_type_params__get(self):
"""
A dictionary of all the parameters in the content type.
(This is not a view, set to change, modifications of the dict will not
be applied otherwise.)
"""
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
| (self) |
Subsets and Splits