Skip to content

Commit

Permalink
perf(respone): Lazy instantiation of the extra headers list object
Browse files Browse the repository at this point in the history
  • Loading branch information
kgriffs committed Feb 13, 2019
1 parent 4a3cef7 commit 03d7835
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
16 changes: 7 additions & 9 deletions docs/api/cookies.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,13 @@ The :py:attr:`~.Request.cookies` attribute is a regular
Setting Cookies
~~~~~~~~~~~~~~~

Setting cookies on a response is done via :py:meth:`~.Response.set_cookie`.

The :py:meth:`~.Response.set_cookie` method should be used instead of
:py:meth:`~.Response.set_header` or :py:meth:`~.Response.append_header`.
With :py:meth:`~.Response.set_header` you cannot set multiple headers
with the same name (which is how multiple cookies are sent to the client).
Furthermore, :py:meth:`~.Response.append_header` appends multiple values
to the same header field in a way that is not compatible with the special
format required by the `Set-Cookie` header.
Setting cookies on a response may be done either via
:py:meth:`~.Response.set_cookie` or :py:meth:`~.Response.append_header`.

One of these methods should be used instead of
:py:meth:`~.Response.set_header`. With :py:meth:`~.Response.set_header` you
cannot set multiple headers with the same name (which is how multiple cookies
are sent to the client).

Simple example:

Expand Down
12 changes: 9 additions & 3 deletions falcon/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,10 @@ def __init__(self, options=None):
# NOTE(kgriffs): Collection of additional headers as a list of raw
# tuples, to use in cases where we need more control over setting
# headers and duplicates are allowable or even necessary.
self._extra_headers = []
#
# PERF(kgriffs): Save some CPU cycles and a few bytes of RAM by
# only instantiating the list object later on IFF it is needed.
self._extra_headers = None

self.options = options if options else ResponseOptions()

Expand Down Expand Up @@ -551,7 +554,7 @@ def append_header(self, name, value):
Note:
While this method can be used to efficiently append raw
Set-Cookie headers to the response, you may find
:py:meth:`~.set_cookie` more convenient.
:py:meth:`~.set_cookie` to be more convenient.
Args:
name (str): Header name (case-insensitive). The restrictions
Expand All @@ -574,7 +577,10 @@ def append_header(self, name, value):
name = name.lower()

if name == 'set-cookie':
self._extra_headers.append((name, value))
if not self._extra_headers:
self._extra_headers = [(name, value)]
else:
self._extra_headers.append((name, value))
else:
if name in self._headers:
value = self._headers[name] + ', ' + value
Expand Down

0 comments on commit 03d7835

Please sign in to comment.