Skip to content

Commit f71838f

Browse files
authored
Fix little problem with type hints and adopt a test to make sure it works in all platform (#1207)
2 parents 4d1cc1a + 4ce8b8f commit f71838f

12 files changed

+73
-72
lines changed

src/flask_sqlalchemy/extension.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
from weakref import WeakKeyDictionary
66

77
import sqlalchemy as sa
8-
import sqlalchemy.event
9-
import sqlalchemy.exc
10-
import sqlalchemy.orm
8+
import sqlalchemy.event as sa_event
9+
import sqlalchemy.exc as sa_exc
10+
import sqlalchemy.orm as sa_orm
1111
from flask import abort
1212
from flask import current_app
1313
from flask import Flask
@@ -129,7 +129,7 @@ def __init__(
129129
metadata: sa.MetaData | None = None,
130130
session_options: dict[str, t.Any] | None = None,
131131
query_class: type[Query] = Query,
132-
model_class: type[Model] | sa.orm.DeclarativeMeta = Model,
132+
model_class: type[Model] | sa_orm.DeclarativeMeta = Model,
133133
engine_options: dict[str, t.Any] | None = None,
134134
add_models_to_shell: bool = True,
135135
):
@@ -341,7 +341,7 @@ def init_app(self, app: Flask) -> None:
341341

342342
def _make_scoped_session(
343343
self, options: dict[str, t.Any]
344-
) -> sa.orm.scoped_session[Session]:
344+
) -> sa_orm.scoped_session[Session]:
345345
"""Create a :class:`sqlalchemy.orm.scoping.scoped_session` around the factory
346346
from :meth:`_make_session_factory`. The result is available as :attr:`session`.
347347
@@ -364,11 +364,11 @@ def _make_scoped_session(
364364
"""
365365
scope = options.pop("scopefunc", _app_ctx_id)
366366
factory = self._make_session_factory(options)
367-
return sa.orm.scoped_session(factory, scope)
367+
return sa_orm.scoped_session(factory, scope)
368368

369369
def _make_session_factory(
370370
self, options: dict[str, t.Any]
371-
) -> sa.orm.sessionmaker[Session]:
371+
) -> sa_orm.sessionmaker[Session]:
372372
"""Create the SQLAlchemy :class:`sqlalchemy.orm.sessionmaker` used by
373373
:meth:`_make_scoped_session`.
374374
@@ -391,7 +391,7 @@ def _make_session_factory(
391391
"""
392392
options.setdefault("class_", Session)
393393
options.setdefault("query_cls", self.Query)
394-
return sa.orm.sessionmaker(db=self, **options)
394+
return sa_orm.sessionmaker(db=self, **options)
395395

396396
def _teardown_commit(self, exc: BaseException | None) -> None:
397397
"""Commit the session at the end of the request if there was not an unhandled
@@ -485,7 +485,7 @@ def __new__(
485485
return Table
486486

487487
def _make_declarative_base(
488-
self, model: type[Model] | sa.orm.DeclarativeMeta
488+
self, model: type[Model] | sa_orm.DeclarativeMeta
489489
) -> type[t.Any]:
490490
"""Create a SQLAlchemy declarative model class. The result is available as
491491
:attr:`Model`.
@@ -506,9 +506,9 @@ def _make_declarative_base(
506506
.. versionchanged:: 2.3
507507
``model`` can be an already created declarative model class.
508508
"""
509-
if not isinstance(model, sa.orm.DeclarativeMeta):
509+
if not isinstance(model, sa_orm.DeclarativeMeta):
510510
metadata = self._make_metadata(None)
511-
model = sa.orm.declarative_base(
511+
model = sa_orm.declarative_base(
512512
metadata=metadata, cls=model, name="Model", metaclass=DefaultMeta
513513
)
514514

@@ -783,7 +783,7 @@ def one_or_404(
783783
"""
784784
try:
785785
return self.session.execute(statement).scalar_one()
786-
except (sa.exc.NoResultFound, sa.exc.MultipleResultsFound):
786+
except (sa_exc.NoResultFound, sa_exc.MultipleResultsFound):
787787
abort(404, description=description)
788788

789789
def paginate(
@@ -862,7 +862,7 @@ def _call_for_binds(
862862
if key is None:
863863
message = f"'SQLALCHEMY_DATABASE_URI' config is not set. {message}"
864864

865-
raise sa.exc.UnboundExecutionError(message) from None
865+
raise sa_exc.UnboundExecutionError(message) from None
866866

867867
metadata = self.metadatas[key]
868868
getattr(metadata, op_name)(bind=engine)
@@ -939,31 +939,31 @@ def _set_rel_query(self, kwargs: dict[str, t.Any]) -> None:
939939

940940
def relationship(
941941
self, *args: t.Any, **kwargs: t.Any
942-
) -> sa.orm.RelationshipProperty[t.Any]:
942+
) -> sa_orm.RelationshipProperty[t.Any]:
943943
"""A :func:`sqlalchemy.orm.relationship` that applies this extension's
944944
:attr:`Query` class for dynamic relationships and backrefs.
945945
946946
.. versionchanged:: 3.0
947947
The :attr:`Query` class is set on ``backref``.
948948
"""
949949
self._set_rel_query(kwargs)
950-
return sa.orm.relationship(*args, **kwargs)
950+
return sa_orm.relationship(*args, **kwargs)
951951

952952
def dynamic_loader(
953953
self, argument: t.Any, **kwargs: t.Any
954-
) -> sa.orm.RelationshipProperty[t.Any]:
954+
) -> sa_orm.RelationshipProperty[t.Any]:
955955
"""A :func:`sqlalchemy.orm.dynamic_loader` that applies this extension's
956956
:attr:`Query` class for relationships and backrefs.
957957
958958
.. versionchanged:: 3.0
959959
The :attr:`Query` class is set on ``backref``.
960960
"""
961961
self._set_rel_query(kwargs)
962-
return sa.orm.dynamic_loader(argument, **kwargs)
962+
return sa_orm.dynamic_loader(argument, **kwargs)
963963

964964
def _relation(
965965
self, *args: t.Any, **kwargs: t.Any
966-
) -> sa.orm.RelationshipProperty[t.Any]:
966+
) -> sa_orm.RelationshipProperty[t.Any]:
967967
"""A :func:`sqlalchemy.orm.relationship` that applies this extension's
968968
:attr:`Query` class for dynamic relationships and backrefs.
969969
@@ -976,8 +976,8 @@ def _relation(
976976
"""
977977
# Deprecated, removed in SQLAlchemy 2.0. Accessed through ``__getattr__``.
978978
self._set_rel_query(kwargs)
979-
f = sa.orm.relation # type: ignore[attr-defined]
980-
return f(*args, **kwargs) # type: ignore[no-any-return]
979+
f = sa_orm.relationship
980+
return f(*args, **kwargs)
981981

982982
def __getattr__(self, name: str) -> t.Any:
983983
if name == "db":
@@ -996,12 +996,12 @@ def __getattr__(self, name: str) -> t.Any:
996996
return self._relation
997997

998998
if name == "event":
999-
return sa.event
999+
return sa_event
10001000

10011001
if name.startswith("_"):
10021002
raise AttributeError(name)
10031003

1004-
for mod in (sa, sa.orm):
1004+
for mod in (sa, sa_orm):
10051005
if hasattr(mod, name):
10061006
return getattr(mod, name)
10071007

src/flask_sqlalchemy/model.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import typing as t
55

66
import sqlalchemy as sa
7-
import sqlalchemy.orm
7+
import sqlalchemy.orm as sa_orm
88

99
from .query import Query
1010

@@ -182,21 +182,21 @@ def should_set_tablename(cls: type) -> bool:
182182
joined-table inheritance. If no primary key is found, the name will be unset.
183183
"""
184184
if cls.__dict__.get("__abstract__", False) or not any(
185-
isinstance(b, sa.orm.DeclarativeMeta) for b in cls.__mro__[1:]
185+
isinstance(b, sa_orm.DeclarativeMeta) for b in cls.__mro__[1:]
186186
):
187187
return False
188188

189189
for base in cls.__mro__:
190190
if "__tablename__" not in base.__dict__:
191191
continue
192192

193-
if isinstance(base.__dict__["__tablename__"], sa.orm.declared_attr):
193+
if isinstance(base.__dict__["__tablename__"], sa_orm.declared_attr):
194194
return False
195195

196196
return not (
197197
base is cls
198198
or base.__dict__.get("__abstract__", False)
199-
or not isinstance(base, sa.orm.DeclarativeMeta)
199+
or not isinstance(base, sa_orm.DeclarativeMeta)
200200
)
201201

202202
return True
@@ -208,7 +208,7 @@ def camel_to_snake_case(name: str) -> str:
208208
return name.lower().lstrip("_")
209209

210210

211-
class DefaultMeta(BindMetaMixin, NameMetaMixin, sa.orm.DeclarativeMeta):
211+
class DefaultMeta(BindMetaMixin, NameMetaMixin, sa_orm.DeclarativeMeta):
212212
"""SQLAlchemy declarative metaclass that provides ``__bind_key__`` and
213213
``__tablename__`` support.
214214
"""

src/flask_sqlalchemy/pagination.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from math import ceil
55

66
import sqlalchemy as sa
7-
import sqlalchemy.orm
7+
import sqlalchemy.orm as sa_orm
88
from flask import abort
99
from flask import request
1010

@@ -336,7 +336,7 @@ def _query_items(self) -> list[t.Any]:
336336

337337
def _query_count(self) -> int:
338338
select = self._query_args["select"]
339-
sub = select.options(sa.orm.lazyload("*")).order_by(None).subquery()
339+
sub = select.options(sa_orm.lazyload("*")).order_by(None).subquery()
340340
session = self._query_args["session"]
341341
out = session.execute(sa.select(sa.func.count()).select_from(sub)).scalar()
342342
return out # type: ignore[no-any-return]

src/flask_sqlalchemy/query.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,15 @@
22

33
import typing as t
44

5-
import sqlalchemy as sa
6-
import sqlalchemy.exc
7-
import sqlalchemy.orm
5+
import sqlalchemy.exc as sa_exc
6+
import sqlalchemy.orm as sa_orm
87
from flask import abort
98

109
from .pagination import Pagination
1110
from .pagination import QueryPagination
1211

1312

14-
class Query(sa.orm.Query): # type: ignore[type-arg]
13+
class Query(sa_orm.Query): # type: ignore[type-arg]
1514
"""SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with some extra methods
1615
useful for querying in a web application.
1716
@@ -58,7 +57,7 @@ def one_or_404(self, description: str | None = None) -> t.Any:
5857
"""
5958
try:
6059
return self.one()
61-
except (sa.exc.NoResultFound, sa.exc.MultipleResultsFound):
60+
except (sa_exc.NoResultFound, sa_exc.MultipleResultsFound):
6261
abort(404, description=description)
6362

6463
def paginate(

src/flask_sqlalchemy/record_queries.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from time import perf_counter
77

88
import sqlalchemy as sa
9-
import sqlalchemy.event
9+
import sqlalchemy.event as sa_event
1010
from flask import current_app
1111
from flask import g
1212
from flask import has_app_context
@@ -96,8 +96,8 @@ def __getitem__(self, key: int) -> object:
9696

9797

9898
def _listen(engine: sa.engine.Engine) -> None:
99-
sa.event.listen(engine, "before_cursor_execute", _record_start, named=True)
100-
sa.event.listen(engine, "after_cursor_execute", _record_end, named=True)
99+
sa_event.listen(engine, "before_cursor_execute", _record_start, named=True)
100+
sa_event.listen(engine, "after_cursor_execute", _record_end, named=True)
101101

102102

103103
def _record_start(context: sa.engine.ExecutionContext, **kwargs: t.Any) -> None:

src/flask_sqlalchemy/session.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
import typing as t
44

55
import sqlalchemy as sa
6-
import sqlalchemy.exc
7-
import sqlalchemy.orm
6+
import sqlalchemy.exc as sa_exc
7+
import sqlalchemy.orm as sa_orm
88
from flask.globals import app_ctx
99

1010
if t.TYPE_CHECKING:
1111
from .extension import SQLAlchemy
1212

1313

14-
class Session(sa.orm.Session):
14+
class Session(sa_orm.Session):
1515
"""A SQLAlchemy :class:`~sqlalchemy.orm.Session` class that chooses what engine to
1616
use based on the bind key associated with the metadata associated with the thing
1717
being queried.
@@ -55,9 +55,9 @@ def get_bind(
5555
if mapper is not None:
5656
try:
5757
mapper = sa.inspect(mapper)
58-
except sa.exc.NoInspectionAvailable as e:
58+
except sa_exc.NoInspectionAvailable as e:
5959
if isinstance(mapper, type):
60-
raise sa.orm.exc.UnmappedClassError(mapper) from e
60+
raise sa_orm.exc.UnmappedClassError(mapper) from e
6161

6262
raise
6363

@@ -88,7 +88,7 @@ def _clause_to_engine(
8888
key = clause.metadata.info["bind_key"]
8989

9090
if key not in engines:
91-
raise sa.exc.UnboundExecutionError(
91+
raise sa_exc.UnboundExecutionError(
9292
f"Bind key '{key}' is not in 'SQLALCHEMY_BINDS' config."
9393
)
9494

src/flask_sqlalchemy/track_modifications.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import typing as t
44

55
import sqlalchemy as sa
6-
import sqlalchemy.event
7-
import sqlalchemy.orm
6+
import sqlalchemy.event as sa_event
7+
import sqlalchemy.orm as sa_orm
88
from flask import current_app
99
from flask import has_app_context
1010
from flask.signals import Namespace # type: ignore[attr-defined]
@@ -29,12 +29,12 @@
2929
"""
3030

3131

32-
def _listen(session: sa.orm.scoped_session[Session]) -> None:
33-
sa.event.listen(session, "before_flush", _record_ops, named=True)
34-
sa.event.listen(session, "before_commit", _record_ops, named=True)
35-
sa.event.listen(session, "before_commit", _before_commit)
36-
sa.event.listen(session, "after_commit", _after_commit)
37-
sa.event.listen(session, "after_rollback", _after_rollback)
32+
def _listen(session: sa_orm.scoped_session[Session]) -> None:
33+
sa_event.listen(session, "before_flush", _record_ops, named=True)
34+
sa_event.listen(session, "before_commit", _record_ops, named=True)
35+
sa_event.listen(session, "before_commit", _before_commit)
36+
sa_event.listen(session, "after_commit", _after_commit)
37+
sa_event.listen(session, "after_rollback", _after_rollback)
3838

3939

4040
def _record_ops(session: Session, **kwargs: t.Any) -> None:

tests/test_legacy_query.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import pytest
77
import sqlalchemy as sa
8-
import sqlalchemy.exc
8+
import sqlalchemy.exc as sa_exc
99
from flask import Flask
1010
from werkzeug.exceptions import NotFound
1111

@@ -15,9 +15,9 @@
1515

1616
@pytest.fixture(autouse=True)
1717
def ignore_query_warning() -> t.Generator[None, None, None]:
18-
if hasattr(sa.exc, "LegacyAPIWarning"):
18+
if hasattr(sa_exc, "LegacyAPIWarning"):
1919
with warnings.catch_warnings():
20-
exc = sa.exc.LegacyAPIWarning
20+
exc = sa_exc.LegacyAPIWarning
2121
warnings.simplefilter("ignore", exc)
2222
yield
2323
else:

0 commit comments

Comments
 (0)