class SimpleTemplateResponse
from django.template.response import SimpleTemplateResponse
Ancestors (MRO)
- builtins.object
- django.http.response.HttpResponseBase
- django.http.response.HttpResponse
- django.template.response.SimpleTemplateResponse
Attribute | Type | Defined in |
---|---|---|
__dict__ |
getset_descriptor
|
django.http.response.HttpResponseBase |
__weakref__ |
getset_descriptor
|
django.http.response.HttpResponseBase |
charset |
property
|
django.http.response.HttpResponseBase |
reason_phrase |
property
|
django.http.response.HttpResponseBase |
content |
property
|
django.template.response.SimpleTemplateResponse |
content |
property
|
django.http.response.HttpResponse |
Attribute | Value | Defined in |
---|---|---|
rendering_attrs |
['template_name', 'context_data', '_post_render_callbacks'] |
django.template.response.SimpleTemplateResponse |
status_code |
200 |
django.http.response.HttpResponseBase |
streaming |
False |
django.http.response.HttpResponse |
def __bytes__(self)
django.http.response.HttpResponse
django.http.response.HttpResponse
Full HTTP message, including headers, as a bytestring.
def serialize(self):
"""Full HTTP message, including headers, as a bytestring."""
return self.serialize_headers() + b"\r\n\r\n" + self.content
django.http.response.HttpResponseBase
HTTP headers as a bytestring.
def serialize_headers(self):
"""HTTP headers as a bytestring."""
return b"\r\n".join(
[
key.encode("ascii") + b": " + value.encode("latin-1")
for key, value in self.headers.items()
]
)
def __contains__(self, header)
django.http.response.HttpResponseBase
Case-insensitive check for a header.
def has_header(self, header):
"""Case-insensitive check for a header."""
return header in self.headers
def __delitem__(self, header)
django.http.response.HttpResponseBase
def __delitem__(self, header):
del self.headers[header]
def __getitem__(self, header)
django.http.response.HttpResponseBase
def __getitem__(self, header):
return self.headers[header]
def __getstate__(self)
django.template.response.SimpleTemplateResponse
Raise an exception if trying to pickle an unrendered response. Pickle only rendered data, not the data used to construct the response.
def __getstate__(self):
"""
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
"""
obj_dict = self.__dict__.copy()
if not self._is_rendered:
raise ContentNotRenderedError(
"The response content must be rendered before it can be pickled."
)
for attr in self.rendering_attrs:
if attr in obj_dict:
del obj_dict[attr]
return obj_dict
def __init__(self, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)
django.template.response.SimpleTemplateResponse
django.template.response.SimpleTemplateResponse
Initialize self. See help(type(self)) for accurate signature.
def __init__(
self,
template,
context=None,
content_type=None,
status=None,
charset=None,
using=None,
headers=None,
):
# It would seem obvious to call these next two members 'template' and
# 'context', but those names are reserved as part of the test Client
# API. To avoid the name collision, we use different names.
self.template_name = template
self.context_data = context
self.using = using
self._post_render_callbacks = []
# _request stores the current request object in subclasses that know
# about requests, like TemplateResponse. It's defined in the base class
# to minimize code duplication.
# It's called self._request because self.request gets overwritten by
# django.test.client.Client. Unlike template_name and context_data,
# _request should not be considered part of the public API.
self._request = None
# content argument doesn't make sense here because it will be replaced
# with rendered template so we always pass empty string in order to
# prevent errors and provide shorter signature.
super().__init__("", content_type, status, charset=charset, headers=headers)
# _is_rendered tracks whether the template and context has been baked
# into a final response.
# Super __init__ doesn't know any better than to set self.content to
# the empty string we just gave it, which wrongly sets _is_rendered
# True, so we initialize it to False after the call to super __init__.
self._is_rendered = False
django.http.response.HttpResponse
Initialize self. See help(type(self)) for accurate signature.
def __init__(self, content=b"", *args, **kwargs):
super().__init__(*args, **kwargs)
# Content is a bytestring. See the `content` property methods.
self.content = content
django.http.response.HttpResponseBase
Initialize self. See help(type(self)) for accurate signature.
def __init__(
self, content_type=None, status=None, reason=None, charset=None, headers=None
):
self.headers = ResponseHeaders(headers)
self._charset = charset
if "Content-Type" not in self.headers:
if content_type is None:
content_type = f"text/html; charset={self.charset}"
self.headers["Content-Type"] = content_type
elif content_type:
raise ValueError(
"'headers' must not contain 'Content-Type' when the "
"'content_type' parameter is provided."
)
self._resource_closers = []
# This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished.
self._handler_class = None
self.cookies = SimpleCookie()
self.closed = False
if status is not None:
try:
self.status_code = int(status)
except (ValueError, TypeError):
raise TypeError("HTTP status code must be an integer.")
if not 100 <= self.status_code <= 599:
raise ValueError("HTTP status code must be an integer from 100 to 599.")
self._reason_phrase = reason
def __iter__(self)
django.template.response.SimpleTemplateResponse
django.template.response.SimpleTemplateResponse
def __iter__(self):
if not self._is_rendered:
raise ContentNotRenderedError(
"The response content must be rendered before it can be iterated over."
)
return super().__iter__()
django.http.response.HttpResponse
def __iter__(self):
return iter(self._container)
def __repr__(self)
django.http.response.HttpResponse
Return repr(self).
def __repr__(self):
return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % {
"cls": self.__class__.__name__,
"status_code": self.status_code,
"content_type": self._content_type_for_repr,
}
def __setitem__(self, header, value)
django.http.response.HttpResponseBase
def __setitem__(self, header, value):
self.headers[header] = value
def add_post_render_callback(self, callback)
django.template.response.SimpleTemplateResponse
Add a new post-rendering callback. If the response has already been rendered, invoke the callback immediately.
def add_post_render_callback(self, callback):
"""Add a new post-rendering callback.
If the response has already been rendered,
invoke the callback immediately.
"""
if self._is_rendered:
callback(self)
else:
self._post_render_callbacks.append(callback)
def close(self)
django.http.response.HttpResponseBase
# The WSGI server must call this method upon completion of the request. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
def close(self):
for closer in self._resource_closers:
try:
closer()
except Exception:
pass
# Free resources that were still referenced.
self._resource_closers.clear()
self.closed = True
signals.request_finished.send(sender=self._handler_class)
def delete_cookie(self, key, path='/', domain=None, samesite=None)
django.http.response.HttpResponseBase
def delete_cookie(self, key, path="/", domain=None, samesite=None):
# Browsers can ignore the Set-Cookie header if the cookie doesn't use
# the secure flag and:
# - the cookie name starts with "__Host-" or "__Secure-", or
# - the samesite is "none".
secure = key.startswith(("__Secure-", "__Host-")) or (
samesite and samesite.lower() == "none"
)
self.set_cookie(
key,
max_age=0,
path=path,
domain=domain,
secure=secure,
expires="Thu, 01 Jan 1970 00:00:00 GMT",
samesite=samesite,
)
def flush(self)
django.http.response.HttpResponseBase
def flush(self):
pass
def get(self, header, alternate=None)
django.http.response.HttpResponseBase
def get(self, header, alternate=None):
return self.headers.get(header, alternate)
def getvalue(self)
django.http.response.HttpResponse
def getvalue(self):
return self.content
def has_header(self, header)
django.http.response.HttpResponseBase
Case-insensitive check for a header.
def has_header(self, header):
"""Case-insensitive check for a header."""
return header in self.headers
def is_rendered(self)
django.template.response.SimpleTemplateResponse
def items(self)
django.http.response.HttpResponseBase
def items(self):
return self.headers.items()
def make_bytes(self, value)
django.http.response.HttpResponseBase
Turn a value into a bytestring encoded in the output charset.
def make_bytes(self, value):
"""Turn a value into a bytestring encoded in the output charset."""
# Per PEP 3333, this response body must be bytes. To avoid returning
# an instance of a subclass, this function returns `bytes(value)`.
# This doesn't make a copy when `value` already contains bytes.
# Handle string types -- we can't rely on force_bytes here because:
# - Python attempts str conversion first
# - when self._charset != 'utf-8' it re-encodes the content
if isinstance(value, (bytes, memoryview)):
return bytes(value)
if isinstance(value, str):
return bytes(value.encode(self.charset))
# Handle non-string types.
return str(value).encode(self.charset)
def readable(self)
django.http.response.HttpResponseBase
def readable(self):
return False
def render(self)
django.template.response.SimpleTemplateResponse
Render (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Return the baked response instance.
def render(self):
"""Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Return the baked response instance.
"""
retval = self
if not self._is_rendered:
self.content = self.rendered_content
for post_callback in self._post_render_callbacks:
newretval = post_callback(retval)
if newretval is not None:
retval = newretval
return retval
def rendered_content(self)
django.template.response.SimpleTemplateResponse
Return the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property.
def resolve_context(self, context)
django.template.response.SimpleTemplateResponse
def resolve_context(self, context):
return context
def resolve_template(self, template)
django.template.response.SimpleTemplateResponse
Accept a template object, path-to-template, or list of paths.
def resolve_template(self, template):
"""Accept a template object, path-to-template, or list of paths."""
if isinstance(template, (list, tuple)):
return select_template(template, using=self.using)
elif isinstance(template, str):
return get_template(template, using=self.using)
else:
return template
def seekable(self)
django.http.response.HttpResponseBase
def seekable(self):
return False
def serialize(self)
django.http.response.HttpResponse
Full HTTP message, including headers, as a bytestring.
def serialize(self):
"""Full HTTP message, including headers, as a bytestring."""
return self.serialize_headers() + b"\r\n\r\n" + self.content
def serialize_headers(self)
django.http.response.HttpResponseBase
HTTP headers as a bytestring.
def serialize_headers(self):
"""HTTP headers as a bytestring."""
return b"\r\n".join(
[
key.encode("ascii") + b": " + value.encode("latin-1")
for key, value in self.headers.items()
]
)
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
django.http.response.HttpResponseBase
Set a cookie. ``expires`` can be: - a string in the correct format, - a naive ``datetime.datetime`` object in UTC, - an aware ``datetime.datetime`` object in any time zone. If it is a ``datetime.datetime`` object then calculate ``max_age``. ``max_age`` can be: - int/float specifying seconds, - ``datetime.timedelta`` object.
def set_cookie(
self,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
samesite=None,
):
"""
Set a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then calculate ``max_age``.
``max_age`` can be:
- int/float specifying seconds,
- ``datetime.timedelta`` object.
"""
self.cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_naive(expires):
expires = timezone.make_aware(expires, datetime.timezone.utc)
delta = expires - datetime.datetime.now(tz=datetime.timezone.utc)
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta += datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires.
expires = None
if max_age is not None:
raise ValueError("'expires' and 'max_age' can't be used together.")
max_age = max(0, delta.days * 86400 + delta.seconds)
else:
self.cookies[key]["expires"] = expires
else:
self.cookies[key]["expires"] = ""
if max_age is not None:
if isinstance(max_age, datetime.timedelta):
max_age = max_age.total_seconds()
self.cookies[key]["max-age"] = int(max_age)
# IE requires expires, so set it if hasn't been already.
if not expires:
self.cookies[key]["expires"] = http_date(time.time() + max_age)
if path is not None:
self.cookies[key]["path"] = path
if domain is not None:
self.cookies[key]["domain"] = domain
if secure:
self.cookies[key]["secure"] = True
if httponly:
self.cookies[key]["httponly"] = True
if samesite:
if samesite.lower() not in ("lax", "none", "strict"):
raise ValueError('samesite must be "lax", "none", or "strict".')
self.cookies[key]["samesite"] = samesite
def set_signed_cookie(self, key, value, salt='', **kwargs)
django.http.response.HttpResponseBase
def set_signed_cookie(self, key, value, salt="", **kwargs):
value = signing.get_cookie_signer(salt=key + salt).sign(value)
return self.set_cookie(key, value, **kwargs)
def setdefault(self, key, value)
django.http.response.HttpResponseBase
Set a header unless it has already been set.
def setdefault(self, key, value):
"""Set a header unless it has already been set."""
self.headers.setdefault(key, value)
def tell(self)
django.http.response.HttpResponse
django.http.response.HttpResponse
def tell(self):
return len(self.content)
django.http.response.HttpResponseBase
def tell(self):
raise OSError(
"This %s instance cannot tell its position" % self.__class__.__name__
)
def writable(self)
django.http.response.HttpResponse
django.http.response.HttpResponse
def writable(self):
return True
django.http.response.HttpResponseBase
def writable(self):
return False
def write(self, content)
django.http.response.HttpResponse
django.http.response.HttpResponse
def write(self, content):
self._container.append(self.make_bytes(content))
django.http.response.HttpResponseBase
def write(self, content):
raise OSError("This %s instance is not writable" % self.__class__.__name__)
def writelines(self, lines)
django.http.response.HttpResponse
django.http.response.HttpResponse
def writelines(self, lines):
for line in lines:
self.write(line)
django.http.response.HttpResponseBase
def writelines(self, lines):
raise OSError("This %s instance is not writable" % self.__class__.__name__)