itsdangerous API Reference
Full documentation for itsdangerous (2.2.0)
itsdangerous.BadData
Python Library Documentation: class BadData in module itsdangerous.exc class BadData(builtins.Exception) | BadData(message: 'str') | | Raised if bad data of any sort was encountered. This is the base | for all exceptions that ItsDangerous defines. | | .. versionadded:: 0.15 | | Method resolution order: | BadData | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, message: 'str') | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
itsdangerous.BadHeader
Python Library Documentation: class BadHeader in module itsdangerous.exc class BadHeader(BadSignature) | BadHeader(message: 'str', payload: 't.Any | None' = None, header: 't.Any | None' = None, original_error: 'Exception | None' = None) | | Raised if a signed header is invalid in some form. This only | happens for serializers that have a header that goes with the | signature. | | .. versionadded:: 0.24 | | Method resolution order: | BadHeader | BadSignature | BadData | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, message: 'str', payload: 't.Any | None' = None, header: 't.Any | None' = None, original_error: 'Exception | None' = None) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from BadData: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from BadData: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
itsdangerous.BadPayload
Python Library Documentation: class BadPayload in module itsdangerous.exc class BadPayload(BadData) | BadPayload(message: 'str', original_error: 'Exception | None' = None) | | Raised if a payload is invalid. This could happen if the payload | is loaded despite an invalid signature, or if there is a mismatch | between the serializer and deserializer. The original exception | that occurred during loading is stored on as :attr:`original_error`. | | .. versionadded:: 0.15 | | Method resolution order: | BadPayload | BadData | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, message: 'str', original_error: 'Exception | None' = None) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from BadData: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from BadData: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
itsdangerous.BadSignature
Python Library Documentation: class BadSignature in module itsdangerous.exc class BadSignature(BadData) | BadSignature(message: 'str', payload: 't.Any | None' = None) | | Raised if a signature does not match. | | Method resolution order: | BadSignature | BadData | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, message: 'str', payload: 't.Any | None' = None) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from BadData: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from BadData: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
itsdangerous.BadTimeSignature
Python Library Documentation: class BadTimeSignature in module itsdangerous.exc class BadTimeSignature(BadSignature) | BadTimeSignature(message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None) | | Raised if a time-based signature is invalid. This is a subclass | of :class:`BadSignature`. | | Method resolution order: | BadTimeSignature | BadSignature | BadData | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from BadData: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from BadData: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
itsdangerous.HMACAlgorithm
Python Library Documentation: class HMACAlgorithm in module itsdangerous.signer
class HMACAlgorithm(SigningAlgorithm)
| HMACAlgorithm(digest_method: 't.Any' = None)
|
| Provides signature generation using HMACs.
|
| Method resolution order:
| HMACAlgorithm
| SigningAlgorithm
| builtins.object
|
| Methods defined here:
|
| __init__(self, digest_method: 't.Any' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| get_signature(self, key: 'bytes', value: 'bytes') -> 'bytes'
| Returns the signature for the given key and value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| default_digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any' from itsdangerous.signer
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_digest_method': 't.Any'}
|
| ----------------------------------------------------------------------
| Methods inherited from SigningAlgorithm:
|
| verify_signature(self, key: 'bytes', value: 'bytes', sig: 'bytes') -> 'bool'
| Verifies the given signature matches the expected
| signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SigningAlgorithm:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
itsdangerous.NoneAlgorithm
Python Library Documentation: class NoneAlgorithm in module itsdangerous.signer
class NoneAlgorithm(SigningAlgorithm)
| Provides an algorithm that does not perform any signing and
| returns an empty signature.
|
| Method resolution order:
| NoneAlgorithm
| SigningAlgorithm
| builtins.object
|
| Methods defined here:
|
| get_signature(self, key: 'bytes', value: 'bytes') -> 'bytes'
| Returns the signature for the given key and value.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from SigningAlgorithm:
|
| verify_signature(self, key: 'bytes', value: 'bytes', sig: 'bytes') -> 'bool'
| Verifies the given signature matches the expected
| signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SigningAlgorithm:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
itsdangerous.Serializer
Python Library Documentation: class Serializer in module itsdangerous.serializer
class Serializer(typing.Generic)
| Serializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| A serializer wraps a :class:`~itsdangerous.signer.Signer` to
| enable serializing and securely signing data other than bytes. It
| can unsign to verify that the data hasn't been changed.
|
| The serializer provides :meth:`dumps` and :meth:`loads`, similar to
| :mod:`json`, and by default uses :mod:`json` internally to serialize
| the data to bytes.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param serializer: An object that provides ``dumps`` and ``loads``
| methods for serializing data to a string. Defaults to
| :attr:`default_serializer`, which defaults to :mod:`json`.
| :param serializer_kwargs: Keyword arguments to pass when calling
| ``serializer.dumps``.
| :param signer: A ``Signer`` class to instantiate when signing data.
| Defaults to :attr:`default_signer`, which defaults to
| :class:`~itsdangerous.signer.Signer`.
| :param signer_kwargs: Keyword arguments to pass when instantiating
| the ``Signer`` class.
| :param fallback_signers: List of signer parameters to try when
| unsigning with the default signer fails. Each item can be a dict
| of ``signer_kwargs``, a ``Signer`` class, or a tuple of
| ``(signer, signer_kwargs)``. Defaults to
| :attr:`default_fallback_signers`.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 2.0
| Removed the default SHA-512 fallback signer from
| ``default_fallback_signers``.
|
| .. versionchanged:: 1.1
| Added support for ``fallback_signers`` and configured a default
| SHA-512 fallback. This fallback is for users who used the yanked
| 1.0.0 release which defaulted to SHA-512.
|
| .. versionchanged:: 0.14
| The ``signer`` and ``signer_kwargs`` parameters were added to
| the constructor.
|
| Method resolution order:
| Serializer
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[Signer]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_payload(self, payload: 'bytes', serializer: '_PDataSerializer[t.Any] | None' = None) -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| loads(self, s: 'str | bytes', salt: 'str | bytes | None' = None, **kwargs: 't.Any') -> 't.Any'
| Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the
| signature validation fails.
|
| loads_unsafe(self, s: 'str | bytes', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_fallback_signers': 'list[dict[str, t.Any] ...
|
| __orig_bases__ = (typing.Generic[~_TSerialized],)
|
| __parameters__ = (~_TSerialized,)
|
| default_fallback_signers = []
|
| default_serializer = <module 'json' from 'C:\\Users\\Youse\\AppData\\....
| JSON (JavaScript Object Notation) <https://json.org> is a subset of
| JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
| interchange format.
|
| :mod:`json` exposes an API familiar to users of the standard library
| :mod:`marshal` and :mod:`pickle` modules. It is derived from a
| version of the externally maintained simplejson library.
|
| Encoding basic Python object hierarchies::
|
| >>> import json
| >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
| '["foo", {"bar": ["baz", null, 1.0, 2]}]'
| >>> print(json.dumps("\"foo\bar"))
| "\"foo\bar"
| >>> print(json.dumps('\u1234'))
| "\u1234"
| >>> print(json.dumps('\\'))
| "\\"
| >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
| {"a": 0, "b": 0, "c": 0}
| >>> from io import StringIO
| >>> io = StringIO()
| >>> json.dump(['streaming API'], io)
| >>> io.getvalue()
| '["streaming API"]'
|
| Compact encoding::
|
| >>> import json
| >>> mydict = {'4': 5, '6': 7}
| >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
| '[1,2,3,{"4":5,"6":7}]'
|
| Pretty printing::
|
| >>> import json
| >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
| {
| "4": 5,
| "6": 7
| }
|
| Decoding JSON::
|
| >>> import json
| >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
| >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
| True
| >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
| True
| >>> from io import StringIO
| >>> io = StringIO('["streaming API"]')
| >>> json.load(io)[0] == 'streaming API'
| True
|
| Specializing JSON object decoding::
|
| >>> import json
| >>> def as_complex(dct):
| ... if '__complex__' in dct:
| ... return complex(dct['real'], dct['imag'])
| ... return dct
| ...
| >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
| ... object_hook=as_complex)
| (1+2j)
| >>> from decimal import Decimal
| >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
| True
|
| Specializing JSON object encoding::
|
| >>> import json
| >>> def encode_complex(obj):
| ... if isinstance(obj, complex):
| ... return [obj.real, obj.imag]
| ... raise TypeError(f'Object of type {obj.__class__.__name__} '
| ... f'is not JSON serializable')
| ...
| >>> json.dumps(2 + 1j, default=encode_complex)
| '[2.0, 1.0]'
| >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
| '[2.0, 1.0]'
| >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
| '[2.0, 1.0]'
|
|
| Using json.tool from the shell to validate and pretty-print::
|
| $ echo '{"json":"obj"}' | python -m json.tool
| {
| "json": "obj"
| }
| $ echo '{ 1.2:3.4}' | python -m json.tool
| Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
|
|
| default_signer = <class 'itsdangerous.signer.Signer'>
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
itsdangerous.SignatureExpired
Python Library Documentation: class SignatureExpired in module itsdangerous.exc class SignatureExpired(BadTimeSignature) | SignatureExpired(message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None) | | Raised if a signature timestamp is older than ``max_age``. This | is a subclass of :exc:`BadTimeSignature`. | | Method resolution order: | SignatureExpired | BadTimeSignature | BadSignature | BadData | builtins.Exception | builtins.BaseException | builtins.object | | Methods inherited from BadTimeSignature: | | __init__(self, message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from BadData: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from BadData: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
itsdangerous.Signer
Python Library Documentation: class Signer in module itsdangerous.signer
class Signer(builtins.object)
| Signer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
|
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
| Methods defined here:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| derive_key(self, secret_key: 'str | bytes | None' = None) -> 'bytes'
| This method is called to derive the key. The default key
| derivation choices can be overridden here. Key derivation is not
| intended to be used as a security method to make a complex key
| out of a short password. Instead you should use large random
| secret keys.
|
| :param secret_key: A specific secret key to derive from.
| Defaults to the last item in :attr:`secret_keys`.
|
| .. versionchanged:: 2.0
| Added the ``secret_key`` parameter.
|
| get_signature(self, value: 'str | bytes') -> 'bytes'
| Returns the signature for the given value.
|
| sign(self, value: 'str | bytes') -> 'bytes'
| Signs the given string.
|
| unsign(self, signed_value: 'str | bytes') -> 'bytes'
| Unsigns the given string.
|
| validate(self, signed_value: 'str | bytes') -> 'bool'
| Only validates the given signed value. Returns ``True`` if
| the signature exists and is valid.
|
| verify_signature(self, value: 'str | bytes', sig: 'str | bytes') -> 'bool'
| Verifies the signature for the given value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| default_digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any' from itsdangerous.signer
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_digest_method': 't.Any', 'default_key_deri...
|
| default_key_derivation = 'django-concat'
itsdangerous.TimedSerializer
Python Library Documentation: class TimedSerializer in module itsdangerous.timed
class TimedSerializer(itsdangerous.serializer.Serializer)
| TimedSerializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Uses :class:`TimestampSigner` instead of the default
| :class:`.Signer`.
|
| Method resolution order:
| TimedSerializer
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[TimestampSigner]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| loads(self, s: 'str | bytes', max_age: 'int | None' = None, return_timestamp: 'bool' = False, salt: 'str | bytes | None' = None) -> 't.Any'
| Reverse of :meth:`dumps`, raises :exc:`.BadSignature` if the
| signature validation fails. If a ``max_age`` is provided it will
| ensure the signature is not older than that time in seconds. In
| case the signature is outdated, :exc:`.SignatureExpired` is
| raised. All arguments are forwarded to the signer's
| :meth:`~TimestampSigner.unsign` method.
|
| loads_unsafe(self, s: 'str | bytes', max_age: 'int | None' = None, salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_signer': 'type[TimestampSigner]'}
|
| __orig_bases__ = (itsdangerous.serializer.Serializer[~_TSerialized],)
|
| __parameters__ = (~_TSerialized,)
|
| default_signer = <class 'itsdangerous.timed.TimestampSigner'>
| Works like the regular :class:`.Signer` but also records the time
| of the signing and can be used to expire signatures. The
| :meth:`unsign` method can raise :exc:`.SignatureExpired` if the
| unsigning failed because the signature is expired.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_payload(self, payload: 'bytes', serializer: '_PDataSerializer[t.Any] | None' = None) -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| default_serializer = <module 'json' from 'C:\\Users\\Youse\\AppData\\....
| JSON (JavaScript Object Notation) <https://json.org> is a subset of
| JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
| interchange format.
|
| :mod:`json` exposes an API familiar to users of the standard library
| :mod:`marshal` and :mod:`pickle` modules. It is derived from a
| version of the externally maintained simplejson library.
|
| Encoding basic Python object hierarchies::
|
| >>> import json
| >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
| '["foo", {"bar": ["baz", null, 1.0, 2]}]'
| >>> print(json.dumps("\"foo\bar"))
| "\"foo\bar"
| >>> print(json.dumps('\u1234'))
| "\u1234"
| >>> print(json.dumps('\\'))
| "\\"
| >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
| {"a": 0, "b": 0, "c": 0}
| >>> from io import StringIO
| >>> io = StringIO()
| >>> json.dump(['streaming API'], io)
| >>> io.getvalue()
| '["streaming API"]'
|
| Compact encoding::
|
| >>> import json
| >>> mydict = {'4': 5, '6': 7}
| >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
| '[1,2,3,{"4":5,"6":7}]'
|
| Pretty printing::
|
| >>> import json
| >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
| {
| "4": 5,
| "6": 7
| }
|
| Decoding JSON::
|
| >>> import json
| >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
| >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
| True
| >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
| True
| >>> from io import StringIO
| >>> io = StringIO('["streaming API"]')
| >>> json.load(io)[0] == 'streaming API'
| True
|
| Specializing JSON object decoding::
|
| >>> import json
| >>> def as_complex(dct):
| ... if '__complex__' in dct:
| ... return complex(dct['real'], dct['imag'])
| ... return dct
| ...
| >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
| ... object_hook=as_complex)
| (1+2j)
| >>> from decimal import Decimal
| >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
| True
|
| Specializing JSON object encoding::
|
| >>> import json
| >>> def encode_complex(obj):
| ... if isinstance(obj, complex):
| ... return [obj.real, obj.imag]
| ... raise TypeError(f'Object of type {obj.__class__.__name__} '
| ... f'is not JSON serializable')
| ...
| >>> json.dumps(2 + 1j, default=encode_complex)
| '[2.0, 1.0]'
| >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
| '[2.0, 1.0]'
| >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
| '[2.0, 1.0]'
|
|
| Using json.tool from the shell to validate and pretty-print::
|
| $ echo '{"json":"obj"}' | python -m json.tool
| {
| "json": "obj"
| }
| $ echo '{ 1.2:3.4}' | python -m json.tool
| Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
itsdangerous.TimestampSigner
Python Library Documentation: class TimestampSigner in module itsdangerous.timed
class TimestampSigner(itsdangerous.signer.Signer)
| TimestampSigner(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
|
| Works like the regular :class:`.Signer` but also records the time
| of the signing and can be used to expire signatures. The
| :meth:`unsign` method can raise :exc:`.SignatureExpired` if the
| unsigning failed because the signature is expired.
|
| Method resolution order:
| TimestampSigner
| itsdangerous.signer.Signer
| builtins.object
|
| Methods defined here:
|
| get_timestamp(self) -> 'int'
| Returns the current timestamp. The function must return an
| integer.
|
| sign(self, value: 'str | bytes') -> 'bytes'
| Signs the given string and also attaches time information.
|
| timestamp_to_datetime(self, ts: 'int') -> 'datetime'
| Convert the timestamp from :meth:`get_timestamp` into an
| aware :class`datetime.datetime` in UTC.
|
| .. versionchanged:: 2.0
| The timestamp is returned as a timezone-aware ``datetime``
| in UTC rather than a naive ``datetime`` assumed to be UTC.
|
| unsign(self, signed_value: 'str | bytes', max_age: 'int | None' = None, return_timestamp: 'bool' = False) -> 'tuple[bytes, datetime] | bytes'
| Works like the regular :meth:`.Signer.unsign` but can also
| validate the time. See the base docstring of the class for
| the general behavior. If ``return_timestamp`` is ``True`` the
| timestamp of the signature will be returned as an aware
| :class:`datetime.datetime` object in UTC.
|
| .. versionchanged:: 2.0
| The timestamp is returned as a timezone-aware ``datetime``
| in UTC rather than a naive ``datetime`` assumed to be UTC.
|
| validate(self, signed_value: 'str | bytes', max_age: 'int | None' = None) -> 'bool'
| Only validates the given signed value. Returns ``True`` if
| the signature exists and is valid.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.signer.Signer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| derive_key(self, secret_key: 'str | bytes | None' = None) -> 'bytes'
| This method is called to derive the key. The default key
| derivation choices can be overridden here. Key derivation is not
| intended to be used as a security method to make a complex key
| out of a short password. Instead you should use large random
| secret keys.
|
| :param secret_key: A specific secret key to derive from.
| Defaults to the last item in :attr:`secret_keys`.
|
| .. versionchanged:: 2.0
| Added the ``secret_key`` parameter.
|
| get_signature(self, value: 'str | bytes') -> 'bytes'
| Returns the signature for the given value.
|
| verify_signature(self, value: 'str | bytes', sig: 'str | bytes') -> 'bool'
| Verifies the signature for the given value.
|
| ----------------------------------------------------------------------
| Static methods inherited from itsdangerous.signer.Signer:
|
| default_digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any' from itsdangerous.signer
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.signer.Signer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.signer.Signer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.signer.Signer:
|
| default_key_derivation = 'django-concat'
itsdangerous.URLSafeSerializer
Python Library Documentation: class URLSafeSerializer in module itsdangerous.url_safe
class URLSafeSerializer(URLSafeSerializerMixin, itsdangerous.serializer.Serializer)
| URLSafeSerializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Works like :class:`.Serializer` but dumps and loads into a URL
| safe string consisting of the upper and lowercase character of the
| alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
|
| Method resolution order:
| URLSafeSerializer
| URLSafeSerializerMixin
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (<class 'itsdangerous.url_safe.URLSafeSerializerMixin...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from URLSafeSerializerMixin:
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| load_payload(self, payload: 'bytes', *args: 't.Any', serializer: 't.Any | None' = None, **kwargs: 't.Any') -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from URLSafeSerializerMixin:
|
| default_serializer = <class 'itsdangerous._json._CompactJSON'>
| Wrapper around json module that strips whitespace.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[Signer]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| loads(self, s: 'str | bytes', salt: 'str | bytes | None' = None, **kwargs: 't.Any') -> 't.Any'
| Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the
| signature validation fails.
|
| loads_unsafe(self, s: 'str | bytes', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| default_signer = <class 'itsdangerous.signer.Signer'>
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
itsdangerous.URLSafeTimedSerializer
Python Library Documentation: class URLSafeTimedSerializer in module itsdangerous.url_safe
class URLSafeTimedSerializer(URLSafeSerializerMixin, itsdangerous.timed.TimedSerializer)
| URLSafeTimedSerializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Works like :class:`.TimedSerializer` but dumps and loads into a
| URL safe string consisting of the upper and lowercase character of
| the alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
|
| Method resolution order:
| URLSafeTimedSerializer
| URLSafeSerializerMixin
| itsdangerous.timed.TimedSerializer
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (<class 'itsdangerous.url_safe.URLSafeSerializerMixin...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from URLSafeSerializerMixin:
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| load_payload(self, payload: 'bytes', *args: 't.Any', serializer: 't.Any | None' = None, **kwargs: 't.Any') -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from URLSafeSerializerMixin:
|
| default_serializer = <class 'itsdangerous._json._CompactJSON'>
| Wrapper around json module that strips whitespace.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.timed.TimedSerializer:
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[TimestampSigner]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| loads(self, s: 'str | bytes', max_age: 'int | None' = None, return_timestamp: 'bool' = False, salt: 'str | bytes | None' = None) -> 't.Any'
| Reverse of :meth:`dumps`, raises :exc:`.BadSignature` if the
| signature validation fails. If a ``max_age`` is provided it will
| ensure the signature is not older than that time in seconds. In
| case the signature is outdated, :exc:`.SignatureExpired` is
| raised. All arguments are forwarded to the signer's
| :meth:`~TimestampSigner.unsign` method.
|
| loads_unsafe(self, s: 'str | bytes', max_age: 'int | None' = None, salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.timed.TimedSerializer:
|
| default_signer = <class 'itsdangerous.timed.TimestampSigner'>
| Works like the regular :class:`.Signer` but also records the time
| of the signing and can be used to expire signatures. The
| :meth:`unsign` method can raise :exc:`.SignatureExpired` if the
| unsigning failed because the signature is expired.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
itsdangerous.annotations
Python Library Documentation: _Feature in module __future__ object class _Feature(builtins.object) | _Feature(optionalRelease, mandatoryRelease, compiler_flag) | | Methods defined here: | | __init__(self, optionalRelease, mandatoryRelease, compiler_flag) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). | | getMandatoryRelease(self) | Return release in which this feature will become mandatory. | | This is a 5-tuple, of the same form as sys.version_info, or, if | the feature was dropped, or the release date is undetermined, is None. | | getOptionalRelease(self) | Return first release in which this feature was recognized. | | This is a 5-tuple, of the same form as sys.version_info. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
itsdangerous.base64_decode
Python Library Documentation: function base64_decode in module itsdangerous.encoding
base64_decode(string: 'str | bytes') -> 'bytes'
Base64 decode a URL-safe string of bytes or text. The result is
bytes.
itsdangerous.base64_encode
Python Library Documentation: function base64_encode in module itsdangerous.encoding
base64_encode(string: 'str | bytes') -> 'bytes'
Base64 encode a string of bytes or text. The resulting bytes are
safe to use in URLs.
itsdangerous.encoding
Python Library Documentation: module itsdangerous.encoding in itsdangerous
NAME
itsdangerous.encoding
FUNCTIONS
base64_decode(string: 'str | bytes') -> 'bytes'
Base64 decode a URL-safe string of bytes or text. The result is
bytes.
base64_encode(string: 'str | bytes') -> 'bytes'
Base64 encode a string of bytes or text. The resulting bytes are
safe to use in URLs.
bytes_to_int(bytestr: 'bytes') -> 'int'
int_to_bytes(num: 'int') -> 'bytes'
want_bytes(s: 'str | bytes', encoding: 'str' = 'utf-8', errors: 'str' = 'strict') -> 'bytes'
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\itsdangerous\encoding.py
itsdangerous.exc
Python Library Documentation: module itsdangerous.exc in itsdangerous
NAME
itsdangerous.exc
CLASSES
builtins.Exception(builtins.BaseException)
BadData
BadPayload
BadSignature
BadHeader
BadTimeSignature
SignatureExpired
class BadData(builtins.Exception)
| BadData(message: 'str')
|
| Raised if bad data of any sort was encountered. This is the base
| for all exceptions that ItsDangerous defines.
|
| .. versionadded:: 0.15
|
| Method resolution order:
| BadData
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str')
| Initialize self. See help(type(self)) for accurate signature.
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class BadHeader(BadSignature)
| BadHeader(message: 'str', payload: 't.Any | None' = None, header: 't.Any | None' = None, original_error: 'Exception | None' = None)
|
| Raised if a signed header is invalid in some form. This only
| happens for serializers that have a header that goes with the
| signature.
|
| .. versionadded:: 0.24
|
| Method resolution order:
| BadHeader
| BadSignature
| BadData
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', payload: 't.Any | None' = None, header: 't.Any | None' = None, original_error: 'Exception | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from BadData:
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BadData:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class BadPayload(BadData)
| BadPayload(message: 'str', original_error: 'Exception | None' = None)
|
| Raised if a payload is invalid. This could happen if the payload
| is loaded despite an invalid signature, or if there is a mismatch
| between the serializer and deserializer. The original exception
| that occurred during loading is stored on as :attr:`original_error`.
|
| .. versionadded:: 0.15
|
| Method resolution order:
| BadPayload
| BadData
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', original_error: 'Exception | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from BadData:
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BadData:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class BadSignature(BadData)
| BadSignature(message: 'str', payload: 't.Any | None' = None)
|
| Raised if a signature does not match.
|
| Method resolution order:
| BadSignature
| BadData
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', payload: 't.Any | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from BadData:
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BadData:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class BadTimeSignature(BadSignature)
| BadTimeSignature(message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None)
|
| Raised if a time-based signature is invalid. This is a subclass
| of :class:`BadSignature`.
|
| Method resolution order:
| BadTimeSignature
| BadSignature
| BadData
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from BadData:
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BadData:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class SignatureExpired(BadTimeSignature)
| SignatureExpired(message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None)
|
| Raised if a signature timestamp is older than ``max_age``. This
| is a subclass of :exc:`BadTimeSignature`.
|
| Method resolution order:
| SignatureExpired
| BadTimeSignature
| BadSignature
| BadData
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods inherited from BadTimeSignature:
|
| __init__(self, message: 'str', payload: 't.Any | None' = None, date_signed: 'datetime | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from BadData:
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BadData:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\itsdangerous\exc.py
itsdangerous.serializer
Python Library Documentation: module itsdangerous.serializer in itsdangerous
NAME
itsdangerous.serializer
CLASSES
typing.Generic(builtins.object)
Serializer
class Serializer(typing.Generic)
| Serializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| A serializer wraps a :class:`~itsdangerous.signer.Signer` to
| enable serializing and securely signing data other than bytes. It
| can unsign to verify that the data hasn't been changed.
|
| The serializer provides :meth:`dumps` and :meth:`loads`, similar to
| :mod:`json`, and by default uses :mod:`json` internally to serialize
| the data to bytes.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param serializer: An object that provides ``dumps`` and ``loads``
| methods for serializing data to a string. Defaults to
| :attr:`default_serializer`, which defaults to :mod:`json`.
| :param serializer_kwargs: Keyword arguments to pass when calling
| ``serializer.dumps``.
| :param signer: A ``Signer`` class to instantiate when signing data.
| Defaults to :attr:`default_signer`, which defaults to
| :class:`~itsdangerous.signer.Signer`.
| :param signer_kwargs: Keyword arguments to pass when instantiating
| the ``Signer`` class.
| :param fallback_signers: List of signer parameters to try when
| unsigning with the default signer fails. Each item can be a dict
| of ``signer_kwargs``, a ``Signer`` class, or a tuple of
| ``(signer, signer_kwargs)``. Defaults to
| :attr:`default_fallback_signers`.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 2.0
| Removed the default SHA-512 fallback signer from
| ``default_fallback_signers``.
|
| .. versionchanged:: 1.1
| Added support for ``fallback_signers`` and configured a default
| SHA-512 fallback. This fallback is for users who used the yanked
| 1.0.0 release which defaulted to SHA-512.
|
| .. versionchanged:: 0.14
| The ``signer`` and ``signer_kwargs`` parameters were added to
| the constructor.
|
| Method resolution order:
| Serializer
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[Signer]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_payload(self, payload: 'bytes', serializer: '_PDataSerializer[t.Any] | None' = None) -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| loads(self, s: 'str | bytes', salt: 'str | bytes | None' = None, **kwargs: 't.Any') -> 't.Any'
| Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the
| signature validation fails.
|
| loads_unsafe(self, s: 'str | bytes', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_fallback_signers': 'list[dict[str, t.Any] ...
|
| __orig_bases__ = (typing.Generic[~_TSerialized],)
|
| __parameters__ = (~_TSerialized,)
|
| default_fallback_signers = []
|
| default_serializer = <module 'json' from 'C:\\Users\\Youse\\AppData\\....
| JSON (JavaScript Object Notation) <https://json.org> is a subset of
| JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
| interchange format.
|
| :mod:`json` exposes an API familiar to users of the standard library
| :mod:`marshal` and :mod:`pickle` modules. It is derived from a
| version of the externally maintained simplejson library.
|
| Encoding basic Python object hierarchies::
|
| >>> import json
| >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
| '["foo", {"bar": ["baz", null, 1.0, 2]}]'
| >>> print(json.dumps("\"foo\bar"))
| "\"foo\bar"
| >>> print(json.dumps('\u1234'))
| "\u1234"
| >>> print(json.dumps('\\'))
| "\\"
| >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
| {"a": 0, "b": 0, "c": 0}
| >>> from io import StringIO
| >>> io = StringIO()
| >>> json.dump(['streaming API'], io)
| >>> io.getvalue()
| '["streaming API"]'
|
| Compact encoding::
|
| >>> import json
| >>> mydict = {'4': 5, '6': 7}
| >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
| '[1,2,3,{"4":5,"6":7}]'
|
| Pretty printing::
|
| >>> import json
| >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
| {
| "4": 5,
| "6": 7
| }
|
| Decoding JSON::
|
| >>> import json
| >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
| >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
| True
| >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
| True
| >>> from io import StringIO
| >>> io = StringIO('["streaming API"]')
| >>> json.load(io)[0] == 'streaming API'
| True
|
| Specializing JSON object decoding::
|
| >>> import json
| >>> def as_complex(dct):
| ... if '__complex__' in dct:
| ... return complex(dct['real'], dct['imag'])
| ... return dct
| ...
| >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
| ... object_hook=as_complex)
| (1+2j)
| >>> from decimal import Decimal
| >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
| True
|
| Specializing JSON object encoding::
|
| >>> import json
| >>> def encode_complex(obj):
| ... if isinstance(obj, complex):
| ... return [obj.real, obj.imag]
| ... raise TypeError(f'Object of type {obj.__class__.__name__} '
| ... f'is not JSON serializable')
| ...
| >>> json.dumps(2 + 1j, default=encode_complex)
| '[2.0, 1.0]'
| >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
| '[2.0, 1.0]'
| >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
| '[2.0, 1.0]'
|
|
| Using json.tool from the shell to validate and pretty-print::
|
| $ echo '{"json":"obj"}' | python -m json.tool
| {
| "json": "obj"
| }
| $ echo '{ 1.2:3.4}' | python -m json.tool
| Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
|
|
| default_signer = <class 'itsdangerous.signer.Signer'>
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
FUNCTIONS
is_text_serializer(serializer: '_PDataSerializer[t.Any]') -> 'te.TypeGuard[_PDataSerializer[str]]'
Checks whether a serializer generates text or binary.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\itsdangerous\serializer.py
itsdangerous.signer
Python Library Documentation: module itsdangerous.signer in itsdangerous
NAME
itsdangerous.signer
CLASSES
builtins.object
Signer
SigningAlgorithm
HMACAlgorithm
NoneAlgorithm
class HMACAlgorithm(SigningAlgorithm)
| HMACAlgorithm(digest_method: 't.Any' = None)
|
| Provides signature generation using HMACs.
|
| Method resolution order:
| HMACAlgorithm
| SigningAlgorithm
| builtins.object
|
| Methods defined here:
|
| __init__(self, digest_method: 't.Any' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| get_signature(self, key: 'bytes', value: 'bytes') -> 'bytes'
| Returns the signature for the given key and value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| default_digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any'
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_digest_method': 't.Any'}
|
| ----------------------------------------------------------------------
| Methods inherited from SigningAlgorithm:
|
| verify_signature(self, key: 'bytes', value: 'bytes', sig: 'bytes') -> 'bool'
| Verifies the given signature matches the expected
| signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SigningAlgorithm:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class NoneAlgorithm(SigningAlgorithm)
| Provides an algorithm that does not perform any signing and
| returns an empty signature.
|
| Method resolution order:
| NoneAlgorithm
| SigningAlgorithm
| builtins.object
|
| Methods defined here:
|
| get_signature(self, key: 'bytes', value: 'bytes') -> 'bytes'
| Returns the signature for the given key and value.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from SigningAlgorithm:
|
| verify_signature(self, key: 'bytes', value: 'bytes', sig: 'bytes') -> 'bool'
| Verifies the given signature matches the expected
| signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SigningAlgorithm:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Signer(builtins.object)
| Signer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
|
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
| Methods defined here:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| derive_key(self, secret_key: 'str | bytes | None' = None) -> 'bytes'
| This method is called to derive the key. The default key
| derivation choices can be overridden here. Key derivation is not
| intended to be used as a security method to make a complex key
| out of a short password. Instead you should use large random
| secret keys.
|
| :param secret_key: A specific secret key to derive from.
| Defaults to the last item in :attr:`secret_keys`.
|
| .. versionchanged:: 2.0
| Added the ``secret_key`` parameter.
|
| get_signature(self, value: 'str | bytes') -> 'bytes'
| Returns the signature for the given value.
|
| sign(self, value: 'str | bytes') -> 'bytes'
| Signs the given string.
|
| unsign(self, signed_value: 'str | bytes') -> 'bytes'
| Unsigns the given string.
|
| validate(self, signed_value: 'str | bytes') -> 'bool'
| Only validates the given signed value. Returns ``True`` if
| the signature exists and is valid.
|
| verify_signature(self, value: 'str | bytes', sig: 'str | bytes') -> 'bool'
| Verifies the signature for the given value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| default_digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any'
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_digest_method': 't.Any', 'default_key_deri...
|
| default_key_derivation = 'django-concat'
class SigningAlgorithm(builtins.object)
| Subclasses must implement :meth:`get_signature` to provide
| signature generation functionality.
|
| Methods defined here:
|
| get_signature(self, key: 'bytes', value: 'bytes') -> 'bytes'
| Returns the signature for the given key and value.
|
| verify_signature(self, key: 'bytes', value: 'bytes', sig: 'bytes') -> 'bool'
| Verifies the given signature matches the expected
| signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\itsdangerous\signer.py
itsdangerous.t
Python Library Documentation: module typing
NAME
typing - The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
MODULE REFERENCE
https://docs.python.org/3.12/library/typing.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
Among other things, the module includes the following:
* Generic, Protocol, and internal machinery to support generic aliases.
All subscripted types like X[int], Union[int, str] are generic aliases.
* Various "special forms" that have unique meanings in type annotations:
NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.
* Classes whose instances can be type arguments to generic classes and functions:
TypeVar, ParamSpec, TypeVarTuple.
* Public helper functions: get_type_hints, overload, cast, final, and others.
* Several protocols to support duck-typing:
SupportsFloat, SupportsIndex, SupportsAbs, and others.
* Special types: NewType, NamedTuple, TypedDict.
* Deprecated wrapper submodules for re and io related types.
* Deprecated aliases for builtin types and collections.abc ABCs.
Any name not present in __all__ is an implementation detail
that may be changed without notice. Use at your own risk!
CLASSES
builtins.object
builtins.str
Annotated
Any
Generic
IO
BinaryIO
TextIO
Protocol
SupportsAbs
SupportsBytes
SupportsComplex
SupportsFloat
SupportsIndex
SupportsInt
SupportsRound
NewType
ParamSpec
ParamSpecArgs
ParamSpecKwargs
TypeAliasType
TypeVar
TypeVarTuple
_Final(builtins.object)
ForwardRef
class Annotated(builtins.object)
| Annotated(*args, **kwargs)
|
| Add context-specific metadata to a type.
|
| Example: Annotated[int, runtime_check.Unsigned] indicates to the
| hypothetical runtime_check module that this type is an unsigned int.
| Every other consumer of this type can ignore this metadata and treat
| this type as int.
|
| The first argument to Annotated must be a valid type.
|
| Details:
|
| - It's an error to call `Annotated` with less than two arguments.
| - Access the metadata via the ``__metadata__`` attribute::
|
| assert Annotated[int, '$'].__metadata__ == ('$',)
|
| - Nested Annotated types are flattened::
|
| assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
|
| - Instantiating an annotated type is equivalent to instantiating the
| underlying type::
|
| assert Annotated[C, Ann1](5) == C(5)
|
| - Annotated can be used as a generic type alias::
|
| type Optimized[T] = Annotated[T, runtime.Optimize()]
| # type checker will treat Optimized[int]
| # as equivalent to Annotated[int, runtime.Optimize()]
|
| type OptimizedList[T] = Annotated[list[T], runtime.Optimize()]
| # type checker will treat OptimizedList[int]
| # as equivalent to Annotated[list[int], runtime.Optimize()]
|
| - Annotated cannot be used with an unpacked TypeVarTuple::
|
| type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid
|
| This would be equivalent to::
|
| Annotated[T1, T2, T3, ..., Ann1]
|
| where T1, T2 etc. are TypeVars, which would be invalid, because
| only one type should be passed to Annotated.
|
| Class methods defined here:
|
| __class_getitem__(params)
|
| __init_subclass__(*args, **kwargs)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
class Any(builtins.object)
| Any(*args, **kwargs)
|
| Special type indicating an unconstrained type.
|
| - Any is compatible with every type.
| - Any assumed to have all methods.
| - All values assumed to be instances of Any.
|
| Note that all the above statements are true from the point of view of
| static type checkers. At runtime, Any should not be used with instance
| checks.
|
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BinaryIO(IO)
| Typed version of the return of open() in binary mode.
|
| Method resolution order:
| BinaryIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'BinaryIO'
|
| write(self, s: Union[bytes, bytearray]) -> int
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.IO[bytes],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class ForwardRef(_Final)
| ForwardRef(arg, is_argument=True, module=None, *, is_class=False)
|
| Internal wrapper to hold a forward reference.
|
| Method resolution order:
| ForwardRef
| _Final
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, arg, is_argument=True, module=None, *, is_class=False)
| Initialize self. See help(type(self)) for accurate signature.
|
| __or__(self, other)
| Return self|value.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __forward_arg__
|
| __forward_code__
|
| __forward_evaluated__
|
| __forward_is_argument__
|
| __forward_is_class__
|
| __forward_module__
|
| __forward_value__
|
| ----------------------------------------------------------------------
| Class methods inherited from _Final:
|
| __init_subclass__(*args, **kwds)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _Final:
|
| __weakref__
| list of weak references to the object
class Generic(builtins.object)
| Abstract base class for generic types.
|
| On Python 3.12 and newer, generic classes implicitly inherit from
| Generic when they declare a parameter list after the class's name::
|
| class Mapping[KT, VT]:
| def __getitem__(self, key: KT) -> VT:
| ...
| # Etc.
|
| On older versions of Python, however, generic classes have to
| explicitly inherit from Generic.
|
| After a class has been declared to be generic, it can then be used as
| follows::
|
| def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
| try:
| return mapping[key]
| except KeyError:
| return default
|
| Class methods defined here:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
class IO(Generic)
| Generic base class for TextIO and BinaryIO.
|
| This is an abstract, generic version of the return of open().
|
| NOTE: This does not distinguish between the different possible
| classes (text vs. binary, read vs. write vs. read/write,
| append-only, unbuffered). The TextIO and BinaryIO subclasses
| below capture the distinctions between text vs. binary, which is
| pervasive in the interface; however we currently do not offer a
| way to track the other distinctions in the type system.
|
| Method resolution order:
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'IO[AnyStr]'
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~AnyStr],)
|
| __parameters__ = (~AnyStr,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class NewType(builtins.object)
| NewType(name, tp)
|
| NewType creates simple unique types with almost zero runtime overhead.
|
| NewType(name, tp) is considered a subtype of tp
| by static type checkers. At runtime, NewType(name, tp) returns
| a dummy callable that simply returns its argument.
|
| Usage::
|
| UserId = NewType('UserId', int)
|
| def name_by_id(user_id: UserId) -> str:
| ...
|
| UserId('user') # Fails type check
|
| name_by_id(42) # Fails type check
| name_by_id(UserId(42)) # OK
|
| num = UserId(5) + 1 # type: int
|
| Methods defined here:
|
| __init__(self, name, tp)
| Initialize self. See help(type(self)) for accurate signature.
|
| __mro_entries__(self, bases)
|
| __or__(self, other)
| Return self|value.
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __call__ = _idfunc(x, /)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ParamSpec(builtins.object)
| Parameter specification variable.
|
| The preferred way to construct a parameter specification is via the
| dedicated syntax for generic functions, classes, and type aliases,
| where the use of '**' creates a parameter specification::
|
| type IntFunc[**P] = Callable[P, int]
|
| For compatibility with Python 3.11 and earlier, ParamSpec objects
| can also be created as follows::
|
| P = ParamSpec('P')
|
| Parameter specification variables exist primarily for the benefit of
| static type checkers. They are used to forward the parameter types of
| one callable to another callable, a pattern commonly found in
| higher-order functions and decorators. They are only valid when used
| in ``Concatenate``, or as the first argument to ``Callable``, or as
| parameters for user-defined Generics. See class Generic for more
| information on generic types.
|
| An example for annotating a decorator::
|
| def add_logging[**P, T](f: Callable[P, T]) -> Callable[P, T]:
| '''A type-safe decorator to add logging to a function.'''
| def inner(*args: P.args, **kwargs: P.kwargs) -> T:
| logging.info(f'{f.__name__} was called')
| return f(*args, **kwargs)
| return inner
|
| @add_logging
| def add_two(x: float, y: float) -> float:
| '''Add two numbers together.'''
| return x + y
|
| Parameter specification variables can be introspected. e.g.::
|
| >>> P = ParamSpec("P")
| >>> P.__name__
| 'P'
|
| Note that only parameter specification variables defined in the global
| scope can be pickled.
|
| Methods defined here:
|
| __mro_entries__(...)
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __typing_prepare_subst__(self, /, alias, args)
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __bound__
|
| __contravariant__
|
| __covariant__
|
| __infer_variance__
|
| args
| Represents positional arguments.
|
| kwargs
| Represents keyword arguments.
class ParamSpecArgs(builtins.object)
| The args for a ParamSpec object.
|
| Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
|
| ParamSpecArgs objects have a reference back to their ParamSpec::
|
| >>> P = ParamSpec("P")
| >>> P.args.__origin__ is P
| True
|
| This type is meant for runtime introspection and has no special meaning
| to static type checkers.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mro_entries__(...)
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __origin__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class ParamSpecKwargs(builtins.object)
| The kwargs for a ParamSpec object.
|
| Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
|
| ParamSpecKwargs objects have a reference back to their ParamSpec::
|
| >>> P = ParamSpec("P")
| >>> P.kwargs.__origin__ is P
| True
|
| This type is meant for runtime introspection and has no special meaning
| to static type checkers.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mro_entries__(...)
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __origin__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class Protocol(Generic)
| Base class for protocol classes.
|
| Protocol classes are defined as::
|
| class Proto(Protocol):
| def meth(self) -> int:
| ...
|
| Such classes are primarily used with static type checkers that recognize
| structural subtyping (static duck-typing).
|
| For example::
|
| class C:
| def meth(self) -> int:
| return 0
|
| def func(x: Proto) -> int:
| return x.meth()
|
| func(C()) # Passes static type check
|
| See PEP 544 for details. Protocol classes decorated with
| @typing.runtime_checkable act as simple-minded runtime protocols that check
| only the presence of given attributes, ignoring their type signatures.
| Protocol classes can be generic, they are defined as::
|
| class GenProto[T](Protocol):
| def meth(self) -> T:
| ...
|
| Method resolution order:
| Protocol
| Generic
| builtins.object
|
| Class methods defined here:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __parameters__ = ()
|
| __protocol_attrs__ = set()
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsAbs(Protocol)
| SupportsAbs(*args, **kwargs)
|
| An ABC with one abstract method __abs__ that is covariant in its return type.
|
| Method resolution order:
| SupportsAbs
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __abs__(self) -> T
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__abs__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T])
|
| __parameters__ = (T,)
|
| __protocol_attrs__ = {'__abs__'}
|
| __type_params__ = (T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsBytes(Protocol)
| SupportsBytes(*args, **kwargs)
|
| An ABC with one abstract method __bytes__.
|
| Method resolution order:
| SupportsBytes
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __bytes__(self) -> bytes
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__bytes__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__bytes__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsComplex(Protocol)
| SupportsComplex(*args, **kwargs)
|
| An ABC with one abstract method __complex__.
|
| Method resolution order:
| SupportsComplex
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __complex__(self) -> complex
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__complex__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__complex__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsFloat(Protocol)
| SupportsFloat(*args, **kwargs)
|
| An ABC with one abstract method __float__.
|
| Method resolution order:
| SupportsFloat
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __float__(self) -> float
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__float__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__float__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsIndex(Protocol)
| SupportsIndex(*args, **kwargs)
|
| An ABC with one abstract method __index__.
|
| Method resolution order:
| SupportsIndex
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __index__(self) -> int
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__index__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__index__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsInt(Protocol)
| SupportsInt(*args, **kwargs)
|
| An ABC with one abstract method __int__.
|
| Method resolution order:
| SupportsInt
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| __int__(self) -> int
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__int__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__int__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsRound(Protocol)
| SupportsRound(*args, **kwargs)
|
| An ABC with one abstract method __round__ that is covariant in its return type.
|
| Method resolution order:
| SupportsRound
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| __round__(self, ndigits: int = 0) -> T
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__round__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T])
|
| __parameters__ = (T,)
|
| __protocol_attrs__ = {'__round__'}
|
| __type_params__ = (T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
Text = class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
class TextIO(IO)
| Typed version of the return of open() in text mode.
|
| Method resolution order:
| TextIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'TextIO'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| buffer
|
| encoding
|
| errors
|
| line_buffering
|
| newlines
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.IO[str],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class TypeAliasType(builtins.object)
| Type alias.
|
| Type aliases are created through the type statement::
|
| type Alias = int
|
| In this example, Alias and int will be treated equivalently by static
| type checkers.
|
| At runtime, Alias is an instance of TypeAliasType. The __name__
| attribute holds the name of the type alias. The value of the type alias
| is stored in the __value__ attribute. It is evaluated lazily, so the
| value is computed only if the attribute is accessed.
|
| Type aliases can also be generic::
|
| type ListOrSet[T] = list[T] | set[T]
|
| In this case, the type parameters of the alias are stored in the
| __type_params__ attribute.
|
| See PEP 695 for more information.
|
| Methods defined here:
|
| __getitem__(self, key, /)
| Return self[key].
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __parameters__
|
| __type_params__
|
| __value__
class TypeVar(builtins.object)
| Type variable.
|
| The preferred way to construct a type variable is via the dedicated
| syntax for generic functions, classes, and type aliases::
|
| class Sequence[T]: # T is a TypeVar
| ...
|
| This syntax can also be used to create bound and constrained type
| variables::
|
| # S is a TypeVar bound to str
| class StrSequence[S: str]:
| ...
|
| # A is a TypeVar constrained to str or bytes
| class StrOrBytesSequence[A: (str, bytes)]:
| ...
|
| However, if desired, reusable type variables can also be constructed
| manually, like so::
|
| T = TypeVar('T') # Can be anything
| S = TypeVar('S', bound=str) # Can be any subtype of str
| A = TypeVar('A', str, bytes) # Must be exactly str or bytes
|
| Type variables exist primarily for the benefit of static type
| checkers. They serve as the parameters for generic types as well
| as for generic function and type alias definitions.
|
| The variance of type variables is inferred by type checkers when they
| are created through the type parameter syntax and when
| ``infer_variance=True`` is passed. Manually created type variables may
| be explicitly marked covariant or contravariant by passing
| ``covariant=True`` or ``contravariant=True``. By default, manually
| created type variables are invariant. See PEP 484 and PEP 695 for more
| details.
|
| Methods defined here:
|
| __mro_entries__(...)
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __bound__
|
| __constraints__
|
| __contravariant__
|
| __covariant__
|
| __infer_variance__
class TypeVarTuple(builtins.object)
| Type variable tuple. A specialized form of type variable that enables
| variadic generics.
|
| The preferred way to construct a type variable tuple is via the
| dedicated syntax for generic functions, classes, and type aliases,
| where a single '*' indicates a type variable tuple::
|
| def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
| return (*tup[1:], tup[0])
|
| For compatibility with Python 3.11 and earlier, TypeVarTuple objects
| can also be created as follows::
|
| Ts = TypeVarTuple('Ts') # Can be given any name
|
| Just as a TypeVar (type variable) is a placeholder for a single type,
| a TypeVarTuple is a placeholder for an *arbitrary* number of types. For
| example, if we define a generic class using a TypeVarTuple::
|
| class C[*Ts]: ...
|
| Then we can parameterize that class with an arbitrary number of type
| arguments::
|
| C[int] # Fine
| C[int, str] # Also fine
| C[()] # Even this is fine
|
| For more details, see PEP 646.
|
| Note that only TypeVarTuples defined in the global scope can be
| pickled.
|
| Methods defined here:
|
| __iter__(self, /)
| Implement iter(self).
|
| __mro_entries__(...)
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __typing_prepare_subst__(self, /, alias, args)
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
NamedTuple(typename, fields=None, /, **kwargs)
Typed version of namedtuple.
Usage::
class Employee(NamedTuple):
name: str
id: int
This is equivalent to::
Employee = collections.namedtuple('Employee', ['name', 'id'])
The resulting class has an extra __annotations__ attribute, giving a
dict that maps field names to types. (The field names are also in
the _fields attribute, which is part of the namedtuple API.)
An alternative equivalent functional syntax is also accepted::
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
TypedDict(typename, fields=None, /, *, total=True, **kwargs)
A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type such that a type checker will expect all
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime.
Usage::
>>> class Point2D(TypedDict):
... x: int
... y: int
... label: str
...
>>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
>>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
>>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
True
The type info can be accessed via the Point2D.__annotations__ dict, and
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
TypedDict supports an additional equivalent form::
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
By default, all keys must be present in a TypedDict. It is possible
to override this by specifying totality::
class Point2D(TypedDict, total=False):
x: int
y: int
This means that a Point2D TypedDict can have any of the keys omitted. A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.
The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::
class Point2D(TypedDict):
x: int # the "x" key must always be present (Required is the default)
y: NotRequired[int] # the "y" key can be omitted
See PEP 655 for more details on Required and NotRequired.
assert_never(arg: Never, /) -> Never
Statically assert that a line of code is unreachable.
Example::
def int_or_str(arg: int | str) -> None:
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
assert_never(arg)
If a type checker finds that a call to assert_never() is
reachable, it will emit an error.
At runtime, this throws an exception when called.
assert_type(val, typ, /)
Ask a static type checker to confirm that the value is of the given type.
At runtime this does nothing: it returns the first argument unchanged with no
checks or side effects, no matter the actual type of the argument.
When a static type checker encounters a call to assert_type(), it
emits an error if the value is not of the specified type::
def greet(name: str) -> None:
assert_type(name, str) # OK
assert_type(name, int) # type checker error
cast(typ, val)
Cast a value to a type.
This returns the value unchanged. To the type checker this
signals that the return value has the designated type, but at
runtime we intentionally don't check anything (we want this
to be as fast as possible).
clear_overloads()
Clear all overloads in the registry.
dataclass_transform(*, eq_default: bool = True, order_default: bool = False, kw_only_default: bool = False, frozen_default: bool = False, field_specifiers: tuple[typing.Union[type[typing.Any], typing.Callable[..., typing.Any]], ...] = (), **kwargs: Any) -> <class '_IdentityCallable'>
Decorator to mark an object as providing dataclass-like behaviour.
The decorator can be applied to a function, class, or metaclass.
Example usage with a decorator function::
@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
...
return cls
@create_model
class CustomerModel:
id: int
name: str
On a base class::
@dataclass_transform()
class ModelBase: ...
class CustomerModel(ModelBase):
id: int
name: str
On a metaclass::
@dataclass_transform()
class ModelMeta(type): ...
class ModelBase(metaclass=ModelMeta): ...
class CustomerModel(ModelBase):
id: int
name: str
The ``CustomerModel`` classes defined above will
be treated by type checkers similarly to classes created with
``@dataclasses.dataclass``.
For example, type checkers will assume these classes have
``__init__`` methods that accept ``id`` and ``name``.
The arguments to this decorator can be used to customize this behavior:
- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
``True`` or ``False`` if it is omitted by the caller.
- ``order_default`` indicates whether the ``order`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``frozen_default`` indicates whether the ``frozen`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``field_specifiers`` specifies a static list of supported classes
or functions that describe fields, similar to ``dataclasses.field()``.
- Arbitrary other keyword arguments are accepted in order to allow for
possible future extensions.
At runtime, this decorator records its arguments in the
``__dataclass_transform__`` attribute on the decorated object.
It has no other runtime effect.
See PEP 681 for more details.
final(f)
Decorator to indicate final methods and final classes.
Use this decorator to indicate to type checkers that the decorated
method cannot be overridden, and decorated class cannot be subclassed.
For example::
class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
There is no runtime checking of these properties. The decorator
attempts to set the ``__final__`` attribute to ``True`` on the decorated
object to allow runtime introspection.
get_args(tp)
Get type arguments with all substitutions performed.
For unions, basic simplifications used by Union constructor are performed.
Examples::
>>> T = TypeVar('T')
>>> assert get_args(Dict[str, int]) == (str, int)
>>> assert get_args(int) == ()
>>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
>>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
>>> assert get_args(Callable[[], T][int]) == ([], int)
get_origin(tp)
Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
Annotated, and others. Return None for unsupported types.
Examples::
>>> P = ParamSpec('P')
>>> assert get_origin(Literal[42]) is Literal
>>> assert get_origin(int) is None
>>> assert get_origin(ClassVar[int]) is ClassVar
>>> assert get_origin(Generic) is Generic
>>> assert get_origin(Generic[T]) is Generic
>>> assert get_origin(Union[T, int]) is Union
>>> assert get_origin(List[Tuple[T, T]][int]) is list
>>> assert get_origin(P.args) is P
get_overloads(func)
Return all defined overloads for *func* as a sequence.
get_type_hints(obj, globalns=None, localns=None, include_extras=False)
Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals and recursively replaces all
'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include also
inherited members.
TypeError is raised if the argument is not of a type that can contain
annotations, and an empty dictionary is returned if no annotations are
present.
BEWARE -- the behavior of globalns and localns is counterintuitive
(unless you are familiar with how eval() and exec() work). The
search order is locals first, then globals.
- If no dict arguments are passed, an attempt is made to use the
globals from obj (or the respective module's globals for classes),
and these are also used as the locals. If the object does not appear
to have globals, an empty dictionary is used. For classes, the search
order is globals first then locals.
- If one dict argument is passed, it is used for both globals and
locals.
- If two dict arguments are passed, they specify globals and
locals, respectively.
is_typeddict(tp)
Check if an annotation is a TypedDict class.
For example::
>>> from typing import TypedDict
>>> class Film(TypedDict):
... title: str
... year: int
...
>>> is_typeddict(Film)
True
>>> is_typeddict(dict)
False
no_type_check(arg)
Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in place.
no_type_check_decorator(decorator)
Decorator to give another decorator the @no_type_check effect.
This wraps the decorator with something that wraps the decorated
function in @no_type_check.
overload(func)
Decorator for overloaded functions/methods.
In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload.
For example::
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
In a non-stub file (i.e. a regular .py file), do the same but
follow it with an implementation. The implementation should *not*
be decorated with @overload::
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
def utf8(value):
... # implementation goes here
The overloads for a function can be retrieved at runtime using the
get_overloads() function.
override(method: F, /) -> F
Indicate that a method is intended to override a method in a base class.
Usage::
class Base:
def method(self) -> None:
pass
class Child(Base):
@override
def method(self) -> None:
super().method()
When this decorator is applied to a method, the type checker will
validate that it overrides a method or attribute with the same name on a
base class. This helps prevent bugs that may occur when a base class is
changed without an equivalent change to a child class.
There is no runtime checking of this property. The decorator attempts to
set the ``__override__`` attribute to ``True`` on the decorated object to
allow runtime introspection.
See PEP 698 for details.
reveal_type(obj: T, /) -> T
Ask a static type checker to reveal the inferred type of an expression.
When a static type checker encounters a call to ``reveal_type()``,
it will emit the inferred type of the argument::
x: int = 1
reveal_type(x)
Running a static type checker (e.g., mypy) on this example
will produce output similar to 'Revealed type is "builtins.int"'.
At runtime, the function prints the runtime type of the
argument and returns the argument unchanged.
runtime_checkable(cls)
Mark a protocol class as a runtime protocol.
Such protocol can be used with isinstance() and issubclass().
Raise TypeError if applied to a non-protocol class.
This allows a simple-minded structural check very similar to
one trick ponies in collections.abc such as Iterable.
For example::
@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)
Warning: this will check only the presence of the required methods,
not their type signatures!
DATA
AbstractSet = typing.AbstractSet
A generic version of collections.abc.Set.
AnyStr = ~AnyStr
AsyncContextManager = typing.AsyncContextManager
A generic version of contextlib.AbstractAsyncContextManager.
AsyncGenerator = typing.AsyncGenerator
A generic version of collections.abc.AsyncGenerator.
AsyncIterable = typing.AsyncIterable
A generic version of collections.abc.AsyncIterable.
AsyncIterator = typing.AsyncIterator
A generic version of collections.abc.AsyncIterator.
Awaitable = typing.Awaitable
A generic version of collections.abc.Awaitable.
ByteString = typing.ByteString
A generic version of collections.abc.ByteString.
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
ChainMap = typing.ChainMap
A generic version of collections.ChainMap.
ClassVar = typing.ClassVar
Special type construct to mark class variables.
An annotation wrapped in ClassVar indicates that a given
attribute is intended to be used as a class variable and
should not be set on instances of that class.
Usage::
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
ClassVar accepts only types and cannot be further subscribed.
Note that ClassVar is not a class itself, and should not
be used with isinstance() or issubclass().
Collection = typing.Collection
A generic version of collections.abc.Collection.
Concatenate = typing.Concatenate
Special form for annotating higher-order functions.
``Concatenate`` can be used in conjunction with ``ParamSpec`` and
``Callable`` to represent a higher-order function which adds, removes or
transforms the parameters of a callable.
For example::
Callable[Concatenate[int, P], int]
See PEP 612 for detailed information.
Container = typing.Container
A generic version of collections.abc.Container.
ContextManager = typing.ContextManager
A generic version of contextlib.AbstractContextManager.
Coroutine = typing.Coroutine
A generic version of collections.abc.Coroutine.
Counter = typing.Counter
A generic version of collections.Counter.
DefaultDict = typing.DefaultDict
A generic version of collections.defaultdict.
Deque = typing.Deque
A generic version of collections.deque.
Dict = typing.Dict
A generic version of dict.
Final = typing.Final
Special typing construct to indicate final names to type checkers.
A final name cannot be re-assigned or overridden in a subclass.
For example::
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checker
There is no runtime checking of these properties.
FrozenSet = typing.FrozenSet
A generic version of frozenset.
Generator = typing.Generator
A generic version of collections.abc.Generator.
Hashable = typing.Hashable
A generic version of collections.abc.Hashable.
ItemsView = typing.ItemsView
A generic version of collections.abc.ItemsView.
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
Iterator = typing.Iterator
A generic version of collections.abc.Iterator.
KeysView = typing.KeysView
A generic version of collections.abc.KeysView.
List = typing.List
A generic version of list.
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
LiteralString = typing.LiteralString
Represents an arbitrary literal string.
Example::
from typing import LiteralString
def run_query(sql: LiteralString) -> None:
...
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # OK
run_query(literal_string) # OK
run_query("SELECT * FROM " + literal_string) # OK
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
Only string literals and other LiteralStrings are compatible
with LiteralString. This provides a tool to help prevent
security issues such as SQL injection.
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MappingView = typing.MappingView
A generic version of collections.abc.MappingView.
Match = typing.Match
A generic version of re.Match.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
MutableSequence = typing.MutableSequence
A generic version of collections.abc.MutableSequence.
MutableSet = typing.MutableSet
A generic version of collections.abc.MutableSet.
Never = typing.Never
The bottom type, a type that has no members.
This can be used to define a function that should never be
called, or a function that never returns::
from typing import Never
def never_call_me(arg: Never) -> None:
pass
def int_or_str(arg: int | str) -> None:
never_call_me(arg) # type checker error
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
never_call_me(arg) # OK, arg is of type Never
NoReturn = typing.NoReturn
Special type indicating functions that never return.
Example::
from typing import NoReturn
def stop() -> NoReturn:
raise Exception('no way')
NoReturn can also be used as a bottom type, a type that
has no values. Starting in Python 3.11, the Never type should
be used for this concept instead. Type checkers should treat the two
equivalently.
NotRequired = typing.NotRequired
Special typing construct to mark a TypedDict key as potentially missing.
For example::
class Movie(TypedDict):
title: str
year: NotRequired[int]
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
OrderedDict = typing.OrderedDict
A generic version of collections.OrderedDict.
Pattern = typing.Pattern
A generic version of re.Pattern.
Required = typing.Required
Special typing construct to mark a TypedDict key as required.
This is mainly useful for total=False TypedDicts.
For example::
class Movie(TypedDict, total=False):
title: Required[str]
year: int
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
There is no runtime checking that a required key is actually provided
when instantiating a related TypedDict.
Reversible = typing.Reversible
A generic version of collections.abc.Reversible.
Self = typing.Self
Used to spell the type of "self" in classes.
Example::
from typing import Self
class Foo:
def return_self(self) -> Self:
...
return self
This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
Set = typing.Set
A generic version of set.
Sized = typing.Sized
A generic version of collections.abc.Sized.
TYPE_CHECKING = False
Tuple = typing.Tuple
Deprecated alias to builtins.tuple.
Tuple[X, Y] is the cross-product type of X and Y.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
Type = typing.Type
Deprecated alias to builtins.type.
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
joe = new_user(BasicUser)
At this point the type checker knows that joe has type BasicUser.
TypeAlias = typing.TypeAlias
Special form for marking type aliases.
Use TypeAlias to indicate that an assignment should
be recognized as a proper type alias definition by type
checkers.
For example::
Predicate: TypeAlias = Callable[..., bool]
It's invalid when used anywhere except as in the example above.
TypeGuard = typing.TypeGuard
Special typing construct for marking user-defined type guard functions.
``TypeGuard`` can be used to annotate the return type of a user-defined
type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type guard".
Sometimes it would be convenient to use a user-defined boolean function
as a type guard. Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.
Using ``-> TypeGuard`` tells the static type checker that for a given
function:
1. The return value is a boolean.
2. If the return value is ``True``, the type of its argument
is the type inside ``TypeGuard``.
For example::
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``list[object]``.
print("Not a list of strings!")
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
form of ``TypeA`` (it can even be a wider form) and this may lead to
type-unsafe results. The main reason is to allow for things like
narrowing ``list[object]`` to ``list[str]`` even though the latter is not
a subtype of the former, since ``list`` is invariant. The responsibility of
writing type-safe type guards is left to the user.
``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
Unpack = typing.Unpack
Type unpack operator.
The type unpack operator takes the child types from some container type,
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
For example::
# For some generic class `Foo`:
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): ...
Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator::
Foo[*tuple[int, str]]
class Bar(Generic[*Ts]): ...
And from Python 3.12, it can be done using built-in syntax for generics::
Foo[*tuple[int, str]]
class Bar[*Ts]: ...
The operator can also be used along with a `TypedDict` to annotate
`**kwargs` in a function signature::
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
Note that there is only some runtime checking of this operator. Not
everything the runtime allows may be accepted by static type checkers.
For more information, see PEPs 646 and 692.
ValuesView = typing.ValuesView
A generic version of collections.abc.ValuesView.
__all__ = ['Annotated', 'Any', 'Callable', 'ClassVar', 'Concatenate', ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\typing.py
itsdangerous.timed
Python Library Documentation: module itsdangerous.timed in itsdangerous
NAME
itsdangerous.timed
CLASSES
itsdangerous.serializer.Serializer(typing.Generic)
TimedSerializer
itsdangerous.signer.Signer(builtins.object)
TimestampSigner
class TimedSerializer(itsdangerous.serializer.Serializer)
| TimedSerializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Uses :class:`TimestampSigner` instead of the default
| :class:`.Signer`.
|
| Method resolution order:
| TimedSerializer
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[TimestampSigner]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| loads(self, s: 'str | bytes', max_age: 'int | None' = None, return_timestamp: 'bool' = False, salt: 'str | bytes | None' = None) -> 't.Any'
| Reverse of :meth:`dumps`, raises :exc:`.BadSignature` if the
| signature validation fails. If a ``max_age`` is provided it will
| ensure the signature is not older than that time in seconds. In
| case the signature is outdated, :exc:`.SignatureExpired` is
| raised. All arguments are forwarded to the signer's
| :meth:`~TimestampSigner.unsign` method.
|
| loads_unsafe(self, s: 'str | bytes', max_age: 'int | None' = None, salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_signer': 'type[TimestampSigner]'}
|
| __orig_bases__ = (itsdangerous.serializer.Serializer[~_TSerialized],)
|
| __parameters__ = (~_TSerialized,)
|
| default_signer = <class 'itsdangerous.timed.TimestampSigner'>
| Works like the regular :class:`.Signer` but also records the time
| of the signing and can be used to expire signatures. The
| :meth:`unsign` method can raise :exc:`.SignatureExpired` if the
| unsigning failed because the signature is expired.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_payload(self, payload: 'bytes', serializer: '_PDataSerializer[t.Any] | None' = None) -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| default_serializer = <module 'json' from 'C:\\Users\\Youse\\AppData\\....
| JSON (JavaScript Object Notation) <https://json.org> is a subset of
| JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
| interchange format.
|
| :mod:`json` exposes an API familiar to users of the standard library
| :mod:`marshal` and :mod:`pickle` modules. It is derived from a
| version of the externally maintained simplejson library.
|
| Encoding basic Python object hierarchies::
|
| >>> import json
| >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
| '["foo", {"bar": ["baz", null, 1.0, 2]}]'
| >>> print(json.dumps("\"foo\bar"))
| "\"foo\bar"
| >>> print(json.dumps('\u1234'))
| "\u1234"
| >>> print(json.dumps('\\'))
| "\\"
| >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
| {"a": 0, "b": 0, "c": 0}
| >>> from io import StringIO
| >>> io = StringIO()
| >>> json.dump(['streaming API'], io)
| >>> io.getvalue()
| '["streaming API"]'
|
| Compact encoding::
|
| >>> import json
| >>> mydict = {'4': 5, '6': 7}
| >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
| '[1,2,3,{"4":5,"6":7}]'
|
| Pretty printing::
|
| >>> import json
| >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
| {
| "4": 5,
| "6": 7
| }
|
| Decoding JSON::
|
| >>> import json
| >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
| >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
| True
| >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
| True
| >>> from io import StringIO
| >>> io = StringIO('["streaming API"]')
| >>> json.load(io)[0] == 'streaming API'
| True
|
| Specializing JSON object decoding::
|
| >>> import json
| >>> def as_complex(dct):
| ... if '__complex__' in dct:
| ... return complex(dct['real'], dct['imag'])
| ... return dct
| ...
| >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
| ... object_hook=as_complex)
| (1+2j)
| >>> from decimal import Decimal
| >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
| True
|
| Specializing JSON object encoding::
|
| >>> import json
| >>> def encode_complex(obj):
| ... if isinstance(obj, complex):
| ... return [obj.real, obj.imag]
| ... raise TypeError(f'Object of type {obj.__class__.__name__} '
| ... f'is not JSON serializable')
| ...
| >>> json.dumps(2 + 1j, default=encode_complex)
| '[2.0, 1.0]'
| >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
| '[2.0, 1.0]'
| >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
| '[2.0, 1.0]'
|
|
| Using json.tool from the shell to validate and pretty-print::
|
| $ echo '{"json":"obj"}' | python -m json.tool
| {
| "json": "obj"
| }
| $ echo '{ 1.2:3.4}' | python -m json.tool
| Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class TimestampSigner(itsdangerous.signer.Signer)
| TimestampSigner(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
|
| Works like the regular :class:`.Signer` but also records the time
| of the signing and can be used to expire signatures. The
| :meth:`unsign` method can raise :exc:`.SignatureExpired` if the
| unsigning failed because the signature is expired.
|
| Method resolution order:
| TimestampSigner
| itsdangerous.signer.Signer
| builtins.object
|
| Methods defined here:
|
| get_timestamp(self) -> 'int'
| Returns the current timestamp. The function must return an
| integer.
|
| sign(self, value: 'str | bytes') -> 'bytes'
| Signs the given string and also attaches time information.
|
| timestamp_to_datetime(self, ts: 'int') -> 'datetime'
| Convert the timestamp from :meth:`get_timestamp` into an
| aware :class`datetime.datetime` in UTC.
|
| .. versionchanged:: 2.0
| The timestamp is returned as a timezone-aware ``datetime``
| in UTC rather than a naive ``datetime`` assumed to be UTC.
|
| unsign(self, signed_value: 'str | bytes', max_age: 'int | None' = None, return_timestamp: 'bool' = False) -> 'tuple[bytes, datetime] | bytes'
| Works like the regular :meth:`.Signer.unsign` but can also
| validate the time. See the base docstring of the class for
| the general behavior. If ``return_timestamp`` is ``True`` the
| timestamp of the signature will be returned as an aware
| :class:`datetime.datetime` object in UTC.
|
| .. versionchanged:: 2.0
| The timestamp is returned as a timezone-aware ``datetime``
| in UTC rather than a naive ``datetime`` assumed to be UTC.
|
| validate(self, signed_value: 'str | bytes', max_age: 'int | None' = None) -> 'bool'
| Only validates the given signed value. Returns ``True`` if
| the signature exists and is valid.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.signer.Signer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous.Signer', sep: 'str | bytes' = b'.', key_derivation: 'str | None' = None, digest_method: 't.Any | None' = None, algorithm: 'SigningAlgorithm | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| derive_key(self, secret_key: 'str | bytes | None' = None) -> 'bytes'
| This method is called to derive the key. The default key
| derivation choices can be overridden here. Key derivation is not
| intended to be used as a security method to make a complex key
| out of a short password. Instead you should use large random
| secret keys.
|
| :param secret_key: A specific secret key to derive from.
| Defaults to the last item in :attr:`secret_keys`.
|
| .. versionchanged:: 2.0
| Added the ``secret_key`` parameter.
|
| get_signature(self, value: 'str | bytes') -> 'bytes'
| Returns the signature for the given value.
|
| verify_signature(self, value: 'str | bytes', sig: 'str | bytes') -> 'bool'
| Verifies the signature for the given value.
|
| ----------------------------------------------------------------------
| Static methods inherited from itsdangerous.signer.Signer:
|
| default_digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any' from itsdangerous.signer
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.signer.Signer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.signer.Signer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.signer.Signer:
|
| default_key_derivation = 'django-concat'
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\itsdangerous\timed.py
itsdangerous.url_safe
Python Library Documentation: module itsdangerous.url_safe in itsdangerous
NAME
itsdangerous.url_safe
CLASSES
itsdangerous.serializer.Serializer(typing.Generic)
URLSafeSerializerMixin
URLSafeSerializer(URLSafeSerializerMixin, itsdangerous.serializer.Serializer)
URLSafeTimedSerializer(URLSafeSerializerMixin, itsdangerous.timed.TimedSerializer)
class URLSafeSerializer(URLSafeSerializerMixin, itsdangerous.serializer.Serializer)
| URLSafeSerializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Works like :class:`.Serializer` but dumps and loads into a URL
| safe string consisting of the upper and lowercase character of the
| alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
|
| Method resolution order:
| URLSafeSerializer
| URLSafeSerializerMixin
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (<class 'itsdangerous.url_safe.URLSafeSerializerMixin...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from URLSafeSerializerMixin:
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| load_payload(self, payload: 'bytes', *args: 't.Any', serializer: 't.Any | None' = None, **kwargs: 't.Any') -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from URLSafeSerializerMixin:
|
| default_serializer = <class 'itsdangerous._json._CompactJSON'>
| Wrapper around json module that strips whitespace.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[Signer]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| loads(self, s: 'str | bytes', salt: 'str | bytes | None' = None, **kwargs: 't.Any') -> 't.Any'
| Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the
| signature validation fails.
|
| loads_unsafe(self, s: 'str | bytes', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| default_signer = <class 'itsdangerous.signer.Signer'>
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class URLSafeSerializerMixin(itsdangerous.serializer.Serializer)
| URLSafeSerializerMixin(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Mixed in with a regular serializer it will attempt to zlib
| compress the string to make it shorter if necessary. It will also
| base64 encode the string so that it can safely be placed in a URL.
|
| Method resolution order:
| URLSafeSerializerMixin
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| load_payload(self, payload: 'bytes', *args: 't.Any', serializer: 't.Any | None' = None, **kwargs: 't.Any') -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_serializer': '_PDataSerializer[str]'}
|
| __orig_bases__ = (itsdangerous.serializer.Serializer[str],)
|
| __parameters__ = ()
|
| default_serializer = <class 'itsdangerous._json._CompactJSON'>
| Wrapper around json module that strips whitespace.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[Signer]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| loads(self, s: 'str | bytes', salt: 'str | bytes | None' = None, **kwargs: 't.Any') -> 't.Any'
| Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the
| signature validation fails.
|
| loads_unsafe(self, s: 'str | bytes', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| default_signer = <class 'itsdangerous.signer.Signer'>
| A signer securely signs bytes, then unsigns them to verify that
| the value hasn't been changed.
|
| The secret key should be a random string of ``bytes`` and should not
| be saved to code or version control. Different salts should be used
| to distinguish signing in different contexts. See :doc:`/concepts`
| for information about the security of the secret key and salt.
|
| :param secret_key: The secret key to sign and verify with. Can be a
| list of keys, oldest to newest, to support key rotation.
| :param salt: Extra key to combine with ``secret_key`` to distinguish
| signatures in different contexts.
| :param sep: Separator between the signature and value.
| :param key_derivation: How to derive the signing key from the secret
| key and salt. Possible values are ``concat``, ``django-concat``,
| or ``hmac``. Defaults to :attr:`default_key_derivation`, which
| defaults to ``django-concat``.
| :param digest_method: Hash function to use when generating the HMAC
| signature. Defaults to :attr:`default_digest_method`, which
| defaults to :func:`hashlib.sha1`. Note that the security of the
| hash alone doesn't apply when used intermediately in HMAC.
| :param algorithm: A :class:`SigningAlgorithm` instance to use
| instead of building a default :class:`HMACAlgorithm` with the
| ``digest_method``.
|
| .. versionchanged:: 2.0
| Added support for key rotation by passing a list to
| ``secret_key``.
|
| .. versionchanged:: 0.18
| ``algorithm`` was added as an argument to the class constructor.
|
| .. versionchanged:: 0.14
| ``key_derivation`` and ``digest_method`` were added as arguments
| to the class constructor.
|
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class URLSafeTimedSerializer(URLSafeSerializerMixin, itsdangerous.timed.TimedSerializer)
| URLSafeTimedSerializer(secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
|
| Works like :class:`.TimedSerializer` but dumps and loads into a
| URL safe string consisting of the upper and lowercase character of
| the alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
|
| Method resolution order:
| URLSafeTimedSerializer
| URLSafeSerializerMixin
| itsdangerous.timed.TimedSerializer
| itsdangerous.serializer.Serializer
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (<class 'itsdangerous.url_safe.URLSafeSerializerMixin...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from URLSafeSerializerMixin:
|
| dump_payload(self, obj: 't.Any') -> 'bytes'
| Dumps the encoded object. The return value is always bytes.
| If the internal serializer returns text, the value will be
| encoded as UTF-8.
|
| load_payload(self, payload: 'bytes', *args: 't.Any', serializer: 't.Any | None' = None, **kwargs: 't.Any') -> 't.Any'
| Loads the encoded object. This function raises
| :class:`.BadPayload` if the payload is not valid. The
| ``serializer`` parameter can be used to override the serializer
| stored on the class. The encoded ``payload`` should always be
| bytes.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from URLSafeSerializerMixin:
|
| default_serializer = <class 'itsdangerous._json._CompactJSON'>
| Wrapper around json module that strips whitespace.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.timed.TimedSerializer:
|
| iter_unsigners(self, salt: 'str | bytes | None' = None) -> 'cabc.Iterator[TimestampSigner]'
| Iterates over all signers to be tried for unsigning. Starts
| with the configured signer, then constructs each signer
| specified in ``fallback_signers``.
|
| loads(self, s: 'str | bytes', max_age: 'int | None' = None, return_timestamp: 'bool' = False, salt: 'str | bytes | None' = None) -> 't.Any'
| Reverse of :meth:`dumps`, raises :exc:`.BadSignature` if the
| signature validation fails. If a ``max_age`` is provided it will
| ensure the signature is not older than that time in seconds. In
| case the signature is outdated, :exc:`.SignatureExpired` is
| raised. All arguments are forwarded to the signer's
| :meth:`~TimestampSigner.unsign` method.
|
| loads_unsafe(self, s: 'str | bytes', max_age: 'int | None' = None, salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads` but without verifying the signature. This
| is potentially very dangerous to use depending on how your
| serializer works. The return value is ``(signature_valid,
| payload)`` instead of just the payload. The first item will be a
| boolean that indicates if the signature is valid. This function
| never fails.
|
| Use it for debugging only and if you know that your serializer
| module is not exploitable (for example, do not use it with a
| pickle serializer).
|
| .. versionadded:: 0.15
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.timed.TimedSerializer:
|
| default_signer = <class 'itsdangerous.timed.TimestampSigner'>
| Works like the regular :class:`.Signer` but also records the time
| of the signing and can be used to expire signatures. The
| :meth:`unsign` method can raise :exc:`.SignatureExpired` if the
| unsigning failed because the signature is expired.
|
|
| ----------------------------------------------------------------------
| Methods inherited from itsdangerous.serializer.Serializer:
|
| __init__(self, secret_key: 'str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes]', salt: 'str | bytes | None' = b'itsdangerous', serializer: 't.Any | None' = None, serializer_kwargs: 'dict[str, t.Any] | None' = None, signer: 'type[Signer] | None' = None, signer_kwargs: 'dict[str, t.Any] | None' = None, fallback_signers: 'list[dict[str, t.Any] | tuple[type[Signer], dict[str, t.Any]] | type[Signer]] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| dump(self, obj: 't.Any', f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'None'
| Like :meth:`dumps` but dumps into a file. The file handle has
| to be compatible with what the internal serializer expects.
|
| dumps(self, obj: 't.Any', salt: 'str | bytes | None' = None) -> '_TSerialized'
| Returns a signed string serialized with the internal
| serializer. The return value can be either a byte or unicode
| string depending on the format of the internal serializer.
|
| load(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 't.Any'
| Like :meth:`loads` but loads from a file.
|
| load_unsafe(self, f: 't.IO[t.Any]', salt: 'str | bytes | None' = None) -> 'tuple[bool, t.Any]'
| Like :meth:`loads_unsafe` but loads from a file.
|
| .. versionadded:: 0.15
|
| make_signer(self, salt: 'str | bytes | None' = None) -> 'Signer'
| Creates a new instance of the signer to be used. The default
| implementation uses the :class:`.Signer` base class.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from itsdangerous.serializer.Serializer:
|
| secret_key
| The newest (last) entry in the :attr:`secret_keys` list. This
| is for compatibility from before key rotation support was added.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from itsdangerous.serializer.Serializer:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from itsdangerous.serializer.Serializer:
|
| default_fallback_signers = []
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\itsdangerous\url_safe.py
itsdangerous.want_bytes
Python Library Documentation: function want_bytes in module itsdangerous.encoding want_bytes(s: 'str | bytes', encoding: 'str' = 'utf-8', errors: 'str' = 'strict') -> 'bytes'