Repository navigation
Releases
Releases · pedrobtz/py-dazapiz
dazapiz 0.1.0
The first release. dazapiz adds what azure-identity lacks: your
az login carried into Spark, DuckDB and any Azure REST API. Where
azure-identity or msal already does a job, dazapiz calls it. It needs
Python 3.10 or later.
Refresh tokens and credentials
refresh_token_from_az_cli()returns the refresh token of the account
the Azure CLI is signed in as, read fromazureProfile.jsonand
msal_token_cache.jsonwithout runningaz(macOS and Linux; Windows
raisesUnsupportedPlatformError).- When one username is several accounts in the Azure CLI's cache (the same
name in two clouds, or two home accounts),refresh_token_from_az_cli()
takes the one in the profile's cloud and tenant, not the newest (#47). RefreshTokenCredentialredeems a refresh token for access tokens as a
TokenCredential, caching them until five minutes before expiry and
keeping the rotated refresh token.RefreshTokenInfo,SupportsRefreshTokenandAZURE_CLI_CLIENT_ID: a
refresh token always travels with its client ID and tenant; a plain
string or$AZURE_REFRESH_TOKENtakes$AZURE_CLIENT_ID(else the CLI's
client ID) and$AZURE_TENANT_ID(else"common").DeviceCodeCredentialandInteractiveBrowserCredentialsubclass the
azure-identityclasses, keep their token cache in the platform store
under the name"dazapiz"(allow_unencrypted_storage=Truefalls back
to a plain file), and addget_refresh_token(), which signs in if
needed and returns the refresh token from that cache.InteractiveBrowserCredentialwith a redirect URI that is not on
localhost signs in ashttr2::req_oauth_auth_code()does: it prints
the sign-in URL and reads back the callback URL, base64 JSON, or the
code and state shown by the callback page, so it works from
code-server and notebooks in the cloud.app_credential()chooses an API's credential from its own service
principal variables (client_id_env,client_secret_env,
tenant_id_env) and the mode (prod,dev, a single credential
name, or automatic), from the argument or$AZURE_TOKEN_CREDENTIALS;
a partly set service principal raisesValueErrornaming the missing
variable. Indevmode the device code has no persisted cache, so it
prompts on headless Linux too (#39). A$AZURE_TOKEN_CREDENTIALSvalue
thatDefaultAzureCredentialtakes but dazapiz does not build
(AzureDeveloperCliCredential, ...) means automatic, with a warning
(#44).
Spark
spark_storage_conf()builds the Hadoopfs.azure.*keys for Spark
to read ADLS Gen2 with a refresh token, a service principal, workload
or managed identity, or an account key, key for key as
azr::azure_spark_storage_conf()when arguments are explicit. Its
defaults differ fromazr's: a service principal or workload identity
needs$AZURE_CLIENT_IDand$AZURE_TENANT_IDrather than falling back
to the CLI client ID, and managed identity without a client ID is the
system-assigned identity. It returns aSparkStorageConf, a
dict[str, str]whosereprandstrredact the secret, refresh token
and account key.
Azure CLI
az_account_show(),az_is_login(),az_login()andaz_logout()run
theazfound onPATH, with--only-show-errorsand a 10-second
timeout (none foraz_login()).az_login()reuses an existing login
(intotenant_id, if given) unlessforce=True; otherwise it runs
az login --use-device-code, prints the device code and URL asaz
streams them, copies the code to the clipboard when a clipboard tool is
found, and returns the account. Itstimeoutcovers the whole login,
theaz account showchecks included (#37), and atenant_iddomain
matches the account's default domain (#38). Errors:AzCliErrorand its
subclassesAzCliNotFoundError,AzCliNotLoggedInError,
AzCliNonInteractiveError(no TTY or notebook kernel) and
AzCliTimeoutError.
REST client
ApiClient, a smallhttpxclient for one REST API, meant to be
subclassed:fetch()fills{name}path placeholders (URL-encoded; a
conversion or format spec is refused, #45), refuses an absolute URL so
the bearer token never leaves the client's host (#36), leavesNone
query values out (#40), retries 429, 503 and connection failures up to
max_trieswithRetry-After(an invalid or infinite one falls back,
#41) orazr's backoff, parses JSON (application/json,text/json,
+json), XML (application/xml,text/xml,+xml) or text by content
type (#43), and raisesApiError(anhttpx.HTTPStatusError) with the
method, URL, status and body. The bearer token is fetched from the
credential once and renewed five minutes before expiry. Subclasses
that setclient_id_envandclient_secret_envget their credential
fromapp_credential();with SomeApiClient() as client:types
clientas the subclass.fetch(..., parse=f)returnsf(body), typed asf's result, so
parse=Model.model_validateorTypeAdapter(list[Model]).validate_python
validates the body. A body that does not parse, or an exception from
f, raisesResponseParseError, which names the method and URL but not
the body.fetch(json=...)sends a pydantic model as
model_dump(mode="json", by_alias=True, exclude_unset=True)and a
dataclass asdataclasses.asdict(), also when nested;dazapizdoes not
depend on pydantic.verbose=Truelogs requests and responses inazr's format on the
dazapiz.httplogger, throughrich, with long JSON bodies abbreviated
asazr'sformat_json_body(); headers are never logged. Log messages
are plain text, so other handlers print norichmarkup (#42).- For tests:
ApiClienttakes keyword-onlytransport=(such as
httpx.MockTransport) andsleep=(the function retries wait with),
and has a read-onlycredentialproperty.
dazapiz.testing.StaticTokenCredentialis a fakeTokenCredentialthat
returns a fixed token and records the scopes it was asked for.
DuckDB
dazapiz.duckdb(extraduckdb) registers DuckDB Azure secrets as
quakdoes, nameddazapiz_defaultordazapiz_<account>and, with
account, scoped to the account'sabfss://,abfs://,az://and
azure://hosts:set_token_secret(),set_sp_secret(),
set_chain_secret(), andset_credential_secret(), which registers an
access token from anyTokenCredentialand returns itsexpires_on.
list_secrets()andazure_settings()return DuckDB relations;
tune()sets the six Azure read and cache settings. Theazure
extension is installed and loaded when needed.import dazapiznever
importsduckdb; without it,dazapiz.duckdbraisesImportError
namingpip install 'dazapiz[duckdb]'.
Errors and secrets
dazapiz.errors:DazapizError,RefreshTokenNotFoundError,
UnsupportedPlatformError,ApiError,ResponseParseError, and the
AzCliErrorfamily. No refresh token, client secret, account key or
bearer token appears in arepr,str, log record or error message.
Documentation
- A site, https://pedrobtz.github.io/py-dazapiz/: a guide (get started,
REST client with the Petstore example, DuckDB, browser-hosted sign-in,
testing your API client) and an API reference.
Install: pip install dazapiz==0.1.0. On PyPI: https://pypi.org/project/dazapiz/0.1.0/ · Documentation: https://pedrobtz.github.io/py-dazapiz/