Warning: This document is for the development version of molten.

Source code for molten.http.cookies

# This file is a part of molten.
#
# Copyright (C) 2018 CLEARTYPE SRL <bogdan@cleartype.io>
#
# molten is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# molten is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from datetime import datetime, timedelta
from typing import Dict, Optional, Union
from urllib.parse import parse_qsl, urlencode


[docs]class Cookies(Dict[str, str]): """A dictionary of request cookies. """
[docs] @classmethod def parse(cls, cookie_header: str) -> "Cookies": """Turn a cookie header into a Cookies instance. """ cookies = cls() cookie_strings = cookie_header.split(";") for cookie in cookie_strings: for name, value in parse_qsl(cookie.lstrip()): cookies[name] = value return cookies
_COOKIE_DATE_DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] _COOKIE_DATE_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] def _format_cookie_date(date: datetime) -> str: """Formats a cookie expiration date according to [1]. [1]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date """ tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, *_ = date.utctimetuple() day = _COOKIE_DATE_DAYS[tm_wday] month = _COOKIE_DATE_MONTHS[tm_mon - 1] return f"{day}, {tm_mday:02d}-{month}-{tm_year} {tm_hour:02d}:{tm_min:02d}:{tm_sec:02d} GMT"