Utilities for Extension Authors
- outgoing.lookup_netrc(host: str, username: str | None = None, path: str | bytes | PathLike[str] | PathLike[bytes] | None = None) → tuple[str, str][source]
Look up the entry for
hostin the netrc file atpath(default:~/.netrc) and return a pair of the username & password. Ifusernameis specified and it does not equal the username in the file, aNetrcLookupErroris raised.- Raises:
NetrcLookupError – if no entry for
hostor the default entry is present in the netrc file; or ifusernamediffers from the username in the netrc filenetrc.NetrcParseError – if the
netrcmodule encounters an error
- outgoing.resolve_password(password: str | Mapping[str, Any], host: str | None = None, username: str | None = None, configpath: str | Path | None = None) → str[source]
Resolve a configuration password value. If
passwordis a string, it is returned unchanged. Otherwise, it must be a mapping with exactly one element; the key is used as the name of the password scheme, and the value is passed to the corresponding function for retrieving the password.When resolving a password field in an
outgoingconfiguration structure, the configpath and any host/service or username values from the configuration (or host/service/username constants specific to the sending method) should be passed into this function so that they can be made available to any password scheme functions that need them.- Raises:
InvalidPasswordError – if
passwordis invalid or cannot be resolved
- outgoing.resolve_path(path: str | bytes | PathLike[str] | PathLike[bytes], basepath: str | bytes | PathLike[str] | PathLike[bytes] | None = None) → Path[source]
Convert a path to a
pathlib.Pathinstance and resolve it using the same rules for as paths inoutgoingconfiguration files: expand tildes by callingPath.expanduser(), prepend the parent directory ofbasepath(usually the value ofconfigpath) to the path if given, and then resolve the resulting path to make it absolute.- Parameters:
path (path) – the path to resolve
basepath (path) – an optional path to resolve
pathrelative to
- Return type:
- class outgoing.OpenClosable[source]
Bases:
ABC,BaseModelAn abstract base class for creating reentrant context managers. A concrete subclass must define
open()andclose()methods;OpenClosablewill then define__enter__and__exit__methods that keep track of the depth of nestedwithstatements, callingopen()andclose()only when entering & exiting the outermostwith.
Pydantic Types & Models
The senders built into outgoing make heavy use of pydantic for validating
& processing configuration, and some of the custom types & models used are also
of general interest to anyone writing an outgoing extension that also uses
pydantic.
- class outgoing.Path
Converts its input to
pathlib.Pathinstances, including expanding tildes. If there is a field namedconfigpathdeclared before thePathfield and its value is non-None, then the value of thePathfield will be resolved relative to the parent directory of theconfigpathfield; otherwise, it will be resolved relative to the current directory.
- class outgoing.Password[source]
A subclass of
pydantic.SecretStrthat acceptsoutgoingpassword specifiers as input and automatically resolves them usingresolve_password(). Host, username, andconfigpathvalues are passed toresolve_password()as follows:If
Passwordis subclassed and given ahostclass variable naming a field, and if the subclass is then used in a model where a field with that name is declared before thePasswordsubclass field, then when the model is instantiated, the value of the named field will be passed as thehostargument toresolve_password(). (If the named field is not present on the model that uses the subclass, thePasswordfield will fail validation.)Alternatively,
Passwordcan be subclassed withhostset to a class callable (a classmethod or staticmethod), and when that subclass is used in a model being instantiated, the callable will be passed adictof all validated fields declared before the password field; the return value from the callable will then be passed as thehostargument toresolve_password(). (If the callable raises an exception, thePasswordfield will fail validation.)If
Passwordis used in a model without being subclassed, or ifhostis not defined in a subclass, thenNonewill be passed as thehostargument toresolve_password().The
usernameargument toresolve_password()can likewise be defined by subclassingPasswordand definingusernameappropriately.If there is a field named
configpathdeclared before thePasswordfield, then the value ofconfigpathis passed toresolve_password().
For example, if writing a pydantic model for a sender configuration where the host-analogue value is passed in a field named
"service"and for which the username is always"__token__", you would subclassPasswordlike this:class MyPassword(outgoing.Password): host = "service" @staticmethod def username(values: dict[str, Any]) -> str: return "__token__"
and then use it in your model like so:
class MySender(pydantic.BaseModel): configpath: Optional[outgoing.Path] = None service: str password: MyPassword # Must come after `configpath` and `service`! # ... other fields ...
Then, when
MySenderis instantiated, the input to thepasswordfield would be automatically resolved by doing (effectively):my_sender.password = pydantic.SecretStr( resolve_password( my_sender.password, host=my_sender.service, username="__token__", configpath=my_sender.configpath, ) )
Note
As this is a subclass of
pydantic.SecretStr, the value of aPasswordfield is retrieved by calling itsget_secret_value()method.
- class outgoing.StandardPassword[source]
A subclass of
Passwordin whichhostis set to"host"andusernameis set to"username"
- class outgoing.NetrcConfig[source]
A pydantic model usable as a base class for any senders that wish to support both
passwordfields and netrc files. The model accepts the fieldsconfigpath,netrc(a boolean or a file path; defaults toFalse),host(required),username(optional), andpassword(optional). When the model is instantiated, ifpasswordisNonebutnetrcis true or a filepath, the entry forhostis looked up in~/.netrcor the given file, and theusernameandpasswordfields are set to the values found.The model will raise a validation error if any of the following are true:
passwordis set butnetrcis truepasswordis set butusernameis not setusernameis set butpasswordis not set andnetrcis falsenetrcis true or a filepath,usernameis non-None, and the username in the netrc file differs fromusernamenetrcis true or a filepath and no entry can be found in the netrc file
- password: StandardPassword | None