Skip to content

Commit

Permalink
Added info abotu adding cookies using Set-Cookie headers
Browse files Browse the repository at this point in the history
  • Loading branch information
michalpokusa committed Aug 29, 2023
1 parent e671f8e commit 8edcd1b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
5 changes: 4 additions & 1 deletion adafruit_httpserver/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ def __init__(self, headers: Union[str, Dict[str, str]] = None) -> None:
self.add(key, value)

def add(self, field_name: str, value: str):
"""Adds a header with the given field name and value."""
"""
Adds a header with the given field name and value.
Allows adding multiple headers with the same name.
"""
self._add_field_value(field_name.lower(), value)

def get(self, field_name: str, default: str = None) -> Union[str, None]:
Expand Down
4 changes: 2 additions & 2 deletions docs/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,11 @@ You can use cookies to store data on the client side, that will be sent back to
They are often used to store authentication tokens, session IDs, but also to user preferences e.g. theme.

To access cookies, use ``request.cookies`` dictionary.
In order to set cookies, pass ``cookies`` dictionary to ``Response`` constructor.
In order to set cookies, pass ``cookies`` dictionary to ``Response`` constructor or manually add ``Set-Cookie`` header.

.. literalinclude:: ../examples/httpserver_cookies.py
:caption: examples/httpserver_cookies.py
:emphasize-lines: 70,77
:emphasize-lines: 70,74-75,81
:linenos:

Chunked response
Expand Down
6 changes: 5 additions & 1 deletion examples/httpserver_cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import socketpool
import wifi

from adafruit_httpserver import Server, Request, Response, GET
from adafruit_httpserver import Server, Request, Response, GET, Headers


pool = socketpool.SocketPool(wifi.radio)
Expand Down Expand Up @@ -70,6 +70,10 @@ def themed_from_cookie(request: Request):
user_theme = request.cookies.get("theme", "light")
wanted_theme = request.query_params.get("theme", user_theme)

headers = Headers()
headers.add("Set-Cookie", f"cookie1=value1")

Check failure on line 74 in examples/httpserver_cookies.py

View workflow job for this annotation

GitHub Actions / test

Using an f-string that does not have any interpolated variables
headers.add("Set-Cookie", f"cookie2=value2")

Check failure on line 75 in examples/httpserver_cookies.py

View workflow job for this annotation

GitHub Actions / test

Using an f-string that does not have any interpolated variables

return Response(
request,
themed_template(wanted_theme),
Expand Down

0 comments on commit 8edcd1b

Please sign in to comment.