33import logging
44from collections .abc import AsyncGenerator
55from contextlib import asynccontextmanager
6+ from os import environ
7+ from urllib .parse import urlparse
68
79from anyvar .anyvar import create_storage , create_translator
810from fastapi import FastAPI
1820 ServiceOrganization ,
1921 ServiceType ,
2022)
23+ from anyvlm .storage import DEFAULT_STORAGE_URI
24+ from anyvlm .storage .base_storage import Storage
2125from anyvlm .utils .types import (
2226 EndpointTag ,
2327)
@@ -51,6 +55,34 @@ def create_anyvar_client(
5155 return PythonAnyVarClient (translator , storage )
5256
5357
58+ def create_anyvlm_storage (uri : str | None = None ) -> Storage :
59+ """Provide factory to create storage based on `uri`, the ANYVLM_STORAGE_URI
60+ environment value, or the default value if neither is provided.
61+
62+ The URI format is as follows:
63+
64+ `postgresql://[username]:[password]@[domain]/[database]`
65+
66+ :param uri: AnyVLM storage URI
67+ :raises ValueError: if the URI scheme is not supported
68+ :return: AnyVLM storage instance
69+ """
70+ if not uri :
71+ uri = environ .get ("ANYVLM_STORAGE_URI" , DEFAULT_STORAGE_URI )
72+
73+ parsed_uri = urlparse (uri )
74+ if parsed_uri .scheme == "postgresql" :
75+ from anyvlm .storage .postgres import PostgresObjectStore # noqa: PLC0415
76+
77+ storage = PostgresObjectStore (uri )
78+ else :
79+ msg = f"URI scheme { parsed_uri .scheme } is not implemented"
80+ raise ValueError (msg )
81+
82+ _logger .debug ("create_storage: %s → %s}" , storage .sanitized_url , storage )
83+ return storage
84+
85+
5486@asynccontextmanager
5587async def lifespan (app : FastAPI ) -> AsyncGenerator :
5688 """Configure FastAPI instance lifespan.
@@ -59,8 +91,10 @@ async def lifespan(app: FastAPI) -> AsyncGenerator:
5991 :return: async context handler
6092 """
6193 app .state .anyvar_client = create_anyvar_client ()
94+ app .state .anyvlm_storage = create_anyvlm_storage ()
6295 yield
6396 app .state .anyvar_client .close ()
97+ app .state .anyvlm_storage .close ()
6498
6599
66100app = FastAPI (
0 commit comments