add fallback to urlencode the postgres password if it fails

This commit is contained in:
Michael Genson 2024-02-12 16:40:12 +00:00
parent 0ce05c781c
commit e35b2e9fbf

View File

@ -1,5 +1,6 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from pathlib import Path from pathlib import Path
from urllib import parse as urlparse
from pydantic import BaseModel, PostgresDsn from pydantic import BaseModel, PostgresDsn
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
@ -44,15 +45,28 @@ class PostgresProvider(AbstractDBProvider, BaseSettings):
@property @property
def db_url(self) -> str: def db_url(self) -> str:
host = f"{self.POSTGRES_SERVER}:{self.POSTGRES_PORT}" host = f"{self.POSTGRES_SERVER}:{self.POSTGRES_PORT}"
return str( try:
PostgresDsn.build( url = PostgresDsn.build(
scheme="postgresql", scheme="postgresql",
username=self.POSTGRES_USER, username=self.POSTGRES_USER,
password=self.POSTGRES_PASSWORD, password=self.POSTGRES_PASSWORD,
host=host, host=host,
path=f"{self.POSTGRES_DB or ''}", path=f"{self.POSTGRES_DB or ''}",
) )
) except ValueError as outer_error:
try:
# if the password contains special characters, it needs to be URL encoded
url = PostgresDsn.build(
scheme="postgresql",
username=self.POSTGRES_USER,
password=urlparse.quote_plus(self.POSTGRES_PASSWORD),
host=host,
path=f"{self.POSTGRES_DB or ''}",
)
except Exception:
raise outer_error
return str(url)
@property @property
def db_url_public(self) -> str: def db_url_public(self) -> str: