API reference¶
Everything public is re-exported from the top-level zarr_http_server
namespace; the private _serve and _keys modules are implementation detail
and carry no compatibility guarantee.
Building an app¶
zarr_http_server.store_app ¶
store_app(
store: Store,
*,
methods: Set[HTTPMethod] | None = None,
cors_options: CorsOptions | None = None,
max_body_size: int | None = DEFAULT_MAX_BODY_SIZE,
) -> Starlette
Create a Starlette ASGI app that serves every key in a zarr Store.
Parameters:
-
store(Store) –The zarr store to serve.
-
methods(set of HTTPMethod, default:None) –The HTTP methods to accept: any of
"GET","HEAD", and"PUT". Defaults to{"GET"}, which also servesHEAD. Passing any other method raisesValueError. -
cors_options(CorsOptions, default:None) –If provided, CORS middleware will be added with the given options.
-
max_body_size(int or None, default:DEFAULT_MAX_BODY_SIZE) –Largest
PUTbody to accept, in bytes; larger requests get a 413.Store.settakes a wholeBuffer, so bodies cannot be streamed and are held in memory in full. Defaults toDEFAULT_MAX_BODY_SIZE; passNoneto lift the cap.
Returns:
-
Starlette–An ASGI application.
Source code in src/zarr_http_server/_serve.py
zarr_http_server.node_app ¶
node_app(
node: Array[Any] | Group,
*,
methods: Set[HTTPMethod] | None = None,
cors_options: CorsOptions | None = None,
max_body_size: int | None = DEFAULT_MAX_BODY_SIZE,
) -> Starlette
Create a Starlette ASGI app that serves only the keys belonging to a
zarr Array or Group.
For an Array, the served keys are the metadata document(s) and all
chunk (or shard) keys whose coordinates fall within the array's grid.
For a Group, the served keys are the group's own metadata plus any
path that resolves through the group's members to a valid array metadata
document or chunk key.
Requests for keys outside this set receive a 404 response, even if the underlying store contains data at that path.
Parameters:
-
node(Array or Group) –The zarr array or group to serve.
-
methods(set of HTTPMethod, default:None) –The HTTP methods to accept: any of
"GET","HEAD", and"PUT". Defaults to{"GET"}, which also servesHEAD. Passing any other method raisesValueError. -
cors_options(CorsOptions, default:None) –If provided, CORS middleware will be added with the given options.
-
max_body_size(int or None, default:DEFAULT_MAX_BODY_SIZE) –Largest
PUTbody to accept, in bytes; larger requests get a 413.Store.settakes a wholeBuffer, so bodies cannot be streamed and are held in memory in full. Defaults toDEFAULT_MAX_BODY_SIZE; passNoneto lift the cap.
Returns:
-
Starlette–An ASGI application.
Source code in src/zarr_http_server/_serve.py
Running a server¶
zarr_http_server.serve ¶
serve(
app: Starlette,
*,
host: str = "127.0.0.1",
port: int | Literal["auto"] = AUTO_PORT,
shutdown_timeout: int = 5,
uvicorn_options: Mapping[str, object] | None = None,
) -> None
Run an ASGI app under Uvicorn, blocking until it is stopped.
Returns only when the server stops, so this is the shape for a process
whose job is to serve -- a script, a container entrypoint. Use
:func:serve_background when the caller has more to do.
Build the app first with :func:store_app or :func:node_app, or compose
several of them; what an app serves is settled when it is built, and this
only decides how it runs.
.. code-block:: python
serve(store_app(store), host="0.0.0.0", port=8000)
Parameters:
-
app(Starlette) –The ASGI app to run.
-
host(str, default:'127.0.0.1') –The host to bind to. Defaults to
"127.0.0.1". -
port(int, default:AUTO_PORT) –The port to bind to. Defaults to
8000. -
shutdown_timeout(int, default:5) –Seconds to wait for in-flight requests to finish gracefully when the server is shut down, via uvicorn's
timeout_graceful_shutdown. Defaults to5. -
uvicorn_options(Mapping[str, object], default:None) –Extra options passed straight to
uvicorn.Config, merged over the ones set here (host,port,timeout_graceful_shutdown), so a caller key wins. This is the escape hatch for anything uvicorn can do that this signature does not name -- TLS viassl_keyfile/ssl_certfile,proxy_headersandforwarded_allow_ipsbehind a reverse proxy,root_pathwhen mounted under a prefix,log_level,limit_concurrency, or auds/fdbind.
Source code in src/zarr_http_server/_serve.py
zarr_http_server.serve_background ¶
serve_background(
app: Starlette,
*,
host: str = "127.0.0.1",
port: int | Literal["auto"] = AUTO_PORT,
shutdown_timeout: int = 5,
uvicorn_options: Mapping[str, object] | None = None,
) -> BackgroundServer
Start an ASGI app under Uvicorn in a daemon thread and return at once.
Returns once the socket is listening, so the next statement can use the server. The returned handle is also a context manager:
.. code-block:: python
with serve_background(node_app(array)) as server:
httpx.get(f"{server.url}/zarr.json")
In a notebook, where the server must outlive the cell that started it,
keep the handle instead and call :meth:BackgroundServer.shutdown later.
Parameters:
-
app(Starlette) –The ASGI app to run.
-
host(str, default:'127.0.0.1') –The host to bind to. Defaults to
"127.0.0.1". -
port(int, default:AUTO_PORT) –The port to bind to. Defaults to
0, which asks the OS for a free one -- unlike :func:serve, whose caller usually needs a port others already know. A background server is normally reached through :attr:BackgroundServer.url, and a fixed default would make starting a second one, or re-running a notebook cell, fail on a port collision. -
shutdown_timeout(int, default:5) –Seconds to wait for in-flight requests to finish gracefully, both for uvicorn's
timeout_graceful_shutdownand for the wait :meth:BackgroundServer.shutdownuses before forcing the thread closed. Defaults to5. -
uvicorn_options(Mapping[str, object], default:None) –Extra options passed straight to
uvicorn.Config, merged over the ones set here so a caller key wins. See :func:serve. Binding somewhere other than a TCP host and port leaves :attr:BackgroundServer.urlasNone.
Returns:
-
BackgroundServer–A handle for the running server.
Raises:
-
RuntimeError–If the server does not start -- most often because the port is already in use.
Source code in src/zarr_http_server/_serve.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | |
zarr_http_server.BackgroundServer ¶
A running background HTTP server that can be used as a context manager.
Wraps a uvicorn.Server running in a daemon thread. When used as a
context manager the server is shut down automatically on exit.
Parameters:
-
server(Server) –The running uvicorn server instance.
-
thread(Thread) –The daemon thread running the server.
-
host(str or None) –The host the server was asked to bind, or
Nonewhen it is not listening on a TCP socket. -
port(int or None) –The port actually bound, or
Nonewhen the server is not listening on a TCP socket. -
scheme(str, default:'http') –URL scheme the server is reachable over. Defaults to
"http". -
shutdown_timeout(int, default:5) –Seconds to wait for in-flight requests to finish gracefully during :meth:
shutdownbefore forcing the server closed. Defaults to5.
Examples:
>>> with serve_background(node_app(arr)) as server:
... print(f"Listening on {server.host}:{server.port}")
... # server is shut down when the block exits
Source code in src/zarr_http_server/_serve.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
url
property
¶
url: str | None
The base URL of the running server.
None when the server is not listening on a TCP socket -- a unix
socket or an inherited file descriptor has no host and port, and
inventing one would be a URL that connects to nothing.
__init__ ¶
__init__(
server: Server,
thread: Thread,
*,
host: str | None,
port: int | None,
scheme: str = "http",
shutdown_timeout: int = 5,
) -> None
Source code in src/zarr_http_server/_serve.py
shutdown ¶
Signal the server to shut down and wait for it to stop.
Waits for the server thread to exit on its own, then escalates to
force_exit if it has not, so a request wedged outside uvicorn's
loop cannot block here forever.
Raises:
-
RuntimeError–If the thread is still running after both waits. Returning normally would report success for a server that is still bound to its port and still serving, which the caller cannot detect any other way.
Source code in src/zarr_http_server/_serve.py
Configuration¶
zarr_http_server.CorsOptions ¶
Bases: TypedDict
Options forwarded to Starlette's CORSMiddleware.
Every parameter the middleware accepts appears here, so configuring CORS never requires reaching around this package. Keys left out fall back to the defaults described below; a key that is present is used verbatim, including an empty list.
Two defaults differ from Starlette's own, because this server knows
something its caller should not have to. It emits Content-Range on
every ranged response, which is not a CORS-safelisted response header --
with Starlette's empty expose_headers a browser client can read the
bytes but not learn which bytes it got. And it accepts a Range request
header, which Starlette's empty allow_headers would reject at preflight.
expose_headersdefaults to["Content-Range"]allow_headersdefaults to["Range"]
Everything else defaults to the middleware's own value: no origins, GET
only, no credentials, no origin regex, no private-network access, and a
600-second preflight cache.
Source code in src/zarr_http_server/_serve.py
zarr_http_server.HTTPMethod
module-attribute
¶
HTTPMethod = ReadOnlyHTTPMethod | _WriteHTTPMethod
An HTTP method this server implements.
GET and HEAD read a key; PUT writes one. Other verbs are not accepted:
the handler has no behavior for them, so serving them would silently answer
as if they were GET.
zarr_http_server.ReadOnlyHTTPMethod
module-attribute
¶
ReadOnlyHTTPMethod = Literal['GET', 'HEAD']
An HTTP method that cannot modify the store.
Distinguished from HTTPMethod in the type domain, not only at runtime, so a
read-only interface can be declared rather than merely configured: a
parameter annotated AbstractSet[ReadOnlyHTTPMethod] cannot be handed "PUT"
without a type error, whatever the value turns out to be at runtime.
HEAD belongs here because Starlette routes it wherever GET goes, which is
what RFC 9110 §9.3.2 asks of an origin server. It is answered from the value's
size rather than by building and discarding a body.
zarr_http_server.READ_ONLY_HTTP_METHODS
module-attribute
¶
READ_ONLY_HTTP_METHODS: frozenset[ReadOnlyHTTPMethod] = (
frozenset(get_args(ReadOnlyHTTPMethod))
)
Methods that only read. The default for every app in this package.
Naming the set makes a read-only deployment say so at the call site, rather than being the absence of an argument:
store_app(store, methods=READ_ONLY_HTTP_METHODS)
Typed as a set of ReadOnlyHTTPMethod, so a caller building on it keeps the
static guarantee: adding "PUT" to a frozenset[ReadOnlyHTTPMethod] is a
type error, not a runtime surprise.
The stronger guarantee is a read-only store, which holds however methods is
configured -- see store.with_read_only(True).
zarr_http_server.READ_WRITE_HTTP_METHODS
module-attribute
¶
READ_WRITE_HTTP_METHODS: frozenset[HTTPMethod] = frozenset(
get_args(ReadOnlyHTTPMethod)
+ get_args(_WriteHTTPMethod)
)
Methods that read and write. Serving these grants clients write access.
Every writable app must name a method set, so this constant is also what makes
writable deployments findable: grepping for READ_WRITE_HTTP_METHODS (or for
methods= generally) turns up every place that opts in.
zarr_http_server.AUTO_PORT
module-attribute
¶
AUTO_PORT: Literal['auto'] = 'auto'
Sentinel for port: prefer DEFAULT_PORT, but settle for any free port.
An explicit port is a requirement -- it binds that port or fails -- because a
caller who names one usually has something else expecting the server there.
"auto" says the opposite: no particular port is needed, so a collision
should not stop the server from starting. port=0 keeps its usual meaning of
"any free port", with no preference.
zarr_http_server.DEFAULT_PORT
module-attribute
¶
Port tried first when port="auto".
zarr_http_server.DEFAULT_MAX_BODY_SIZE
module-attribute
¶
Default cap on a PUT body, in bytes.
Store.set takes a whole Buffer, so an accepted body is held in memory in
full; the body is read incrementally and abandoned once it passes this cap,
so one request cannot size the server's memory use. Pass
max_body_size=None to lift the cap and read the body whole.