Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Commit 8cd5514

Browse files
authored
Allow password as a callable when using Postgres backend (#250)
* fix: Ensure password is overrideable Removes the explicit naming of the password parameter for asyncpg, and moves the setting of the password to the kwargs. Further adds tests to ensure that the password argument is preserved. * fix: Add typing for kwargs dict
1 parent d0e30cb commit 8cd5514

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

databases/backends/postgres.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def _get_dialect(self) -> Dialect:
4444
def _get_connection_kwargs(self) -> dict:
4545
url_options = self._database_url.options
4646

47-
kwargs = {}
47+
kwargs = {} # type: typing.Dict[str, typing.Any]
4848
min_size = url_options.get("min_size")
4949
max_size = url_options.get("max_size")
5050
ssl = url_options.get("ssl")
@@ -62,15 +62,15 @@ def _get_connection_kwargs(self) -> dict:
6262

6363
async def connect(self) -> None:
6464
assert self._pool is None, "DatabaseBackend is already running"
65-
kwargs = self._get_connection_kwargs()
66-
self._pool = await asyncpg.create_pool(
65+
kwargs = dict(
6766
host=self._database_url.hostname,
6867
port=self._database_url.port,
6968
user=self._database_url.username,
7069
password=self._database_url.password,
7170
database=self._database_url.database,
72-
**kwargs,
7371
)
72+
kwargs.update(self._get_connection_kwargs())
73+
self._pool = await asyncpg.create_pool(**kwargs)
7474

7575
async def disconnect(self) -> None:
7676
assert self._pool is not None, "DatabaseBackend is not running"

tests/test_connection_options.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,24 @@ def test_postgres_explicit_ssl():
4343
assert kwargs == {"ssl": True}
4444

4545

46+
def test_postgres_no_extra_options():
47+
backend = PostgresBackend("postgres://localhost/database")
48+
kwargs = backend._get_connection_kwargs()
49+
assert kwargs == {}
50+
51+
52+
def test_postgres_password_as_callable():
53+
def gen_password():
54+
return "Foo"
55+
56+
backend = PostgresBackend(
57+
"postgres://:password@localhost/database", password=gen_password
58+
)
59+
kwargs = backend._get_connection_kwargs()
60+
assert kwargs == {"password": gen_password}
61+
assert kwargs["password"]() == "Foo"
62+
63+
4664
def test_mysql_pool_size():
4765
backend = MySQLBackend("mysql://localhost/database?min_size=1&max_size=20")
4866
kwargs = backend._get_connection_kwargs()

0 commit comments

Comments
 (0)