Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sim w/o global session (Sourcery refactored) #7

Open
wants to merge 1 commit into
base: simulation-no-global
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions examples/decorators/provide_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,10 @@ def decorator(func: t.Callable[..., RT]) -> t.Callable[..., RT]:
def wrapper(*args, **kwargs) -> RT:
if "session" in kwargs or session_args_idx < len(args):
return func(*args, **kwargs)
else:
bind = Bind.get_instance(bind_name)
bind = Bind.get_instance(bind_name)

with create_session(bind) as session:
return func(*args, session=session, **kwargs)
with create_session(bind) as session:
return func(*args, session=session, **kwargs)
Comment on lines -49 to +52
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function provide_session refactored with the following changes:


return wrapper

Expand Down
8 changes: 5 additions & 3 deletions examples/usrsrv/component/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,12 @@ def __init__(self, session: Session):
self._query = select(EntityMapper)

def get(self, entity_id: EntityID) -> Entity:
dto = self._session.scalars(self._query.filter_by(uuid=entity_id)).one_or_none()
if not dto:
if dto := self._session.scalars(
self._query.filter_by(uuid=entity_id)
).one_or_none():
return Entity(dto)
else:
raise NotFound(entity_id)
return Entity(dto)
Comment on lines -56 to -59
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ORMRepository.get refactored with the following changes:


def save(self, entity: Entity) -> None:
self._session.add(entity.dto)
Expand Down
5 changes: 3 additions & 2 deletions src/quart_sqlalchemy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,9 @@ class EngineConfig(ConfigBase):
@root_validator
def scrub_execution_options(cls, values):
if "execution_options" in values:
execute_options = values["execution_options"].dict(exclude_defaults=True)
if execute_options:
if execute_options := values["execution_options"].dict(
exclude_defaults=True
):
Comment on lines -149 to +151
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EngineConfig.scrub_execution_options refactored with the following changes:

values["execution_options"] = execute_options
return values

Expand Down
2 changes: 1 addition & 1 deletion src/quart_sqlalchemy/framework/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def __init__(
config: t.Optional[SQLAlchemyConfig] = None,
app: t.Optional[Quart] = None,
):
initialize = False if config is None else True
initialize = config is not None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function QuartSQLAlchemy.__init__ refactored with the following changes:

super().__init__(config, initialize=initialize)

if app is not None:
Expand Down
4 changes: 2 additions & 2 deletions src/quart_sqlalchemy/model/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ def accumulate_mappings(class_, attribute) -> t.Dict[str, t.Any]:
if base_class is class_:
continue
args = getattr(base_class, attribute, {})
accumulated.update(args)
accumulated |= args
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function accumulate_mappings refactored with the following changes:


return accumulated

Expand All @@ -316,7 +316,7 @@ def accumulate_tuples_with_mapping(class_, attribute) -> t.Sequence[t.Any]:
args = getattr(base_class, attribute, ())
for arg in args:
if isinstance(arg, t.Mapping):
accumulated_map.update(arg)
accumulated_map |= arg
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function accumulate_tuples_with_mapping refactored with the following changes:

else:
accumulated_args.append(arg)

Expand Down
8 changes: 4 additions & 4 deletions src/quart_sqlalchemy/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,17 @@ def provide_global_contextual_session(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
session_in_args = any(
[isinstance(arg, (sa.orm.Session, sa.ext.asyncio.AsyncSession)) for arg in args]
isinstance(arg, (sa.orm.Session, sa.ext.asyncio.AsyncSession))
for arg in args
)
session_in_kwargs = "session" in kwargs
session_provided = session_in_args or session_in_kwargs

if session_provided:
return func(self, *args, **kwargs)
else:
session = session_proxy()
session = session_proxy()

return func(self, session, *args, **kwargs)
return func(self, session, *args, **kwargs)
Comment on lines -48 to +58
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function provide_global_contextual_session refactored with the following changes:


return wrapper

Expand Down
2 changes: 1 addition & 1 deletion src/quart_sqlalchemy/sim/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def auth_endpoint_security(self):
results = self.authenticator.enforce(security_schemes, session)
authorized_credentials = {}
for result in results:
authorized_credentials.update(result)
authorized_credentials |= result
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function QuartAuth.auth_endpoint_security refactored with the following changes:

g.authorized_credentials = authorized_credentials


Expand Down
18 changes: 10 additions & 8 deletions src/quart_sqlalchemy/sim/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,22 @@
sa = sqlalchemy




class AppSettings(BaseSettings):

class Config:
env_file = ".env", ".secrets.env"

LOAD_BLUEPRINTS: t.List[str] = Field(
default_factory=lambda: list(("quart_sqlalchemy.sim.views.api",))
default_factory=lambda: ["quart_sqlalchemy.sim.views.api"]
)
LOAD_EXTENSIONS: t.List[str] = Field(
default_factory=lambda: list(
(
"quart_sqlalchemy.sim.db.db",
"quart_sqlalchemy.sim.app.schema",
"quart_sqlalchemy.sim.auth.auth",
)
)
default_factory=lambda: [
"quart_sqlalchemy.sim.db.db",
"quart_sqlalchemy.sim.app.schema",
"quart_sqlalchemy.sim.auth.auth",
]
Comment on lines +19 to +34
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 24-33 refactored with the following changes:

)
SECURITY_SCHEMES: t.Dict[str, SecuritySchemeBase] = Field(
default_factory=lambda: {
Expand All @@ -52,4 +53,5 @@ class Config:
WEB3_HTTPS_PROVIDER_URI: str = Field(env="WEB3_HTTPS_PROVIDER_URI")



settings = AppSettings()
10 changes: 2 additions & 8 deletions src/quart_sqlalchemy/sim/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,13 @@ def process_bind_param(self, value, dialect):
"""Data going into to the database will be transformed by this method.
See ``ObjectID`` for the design and rational for this.
"""
if value is None:
return None

return ObjectID(value).decode()
return None if value is None else ObjectID(value).decode()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ObjectIDType.process_bind_param refactored with the following changes:


def process_result_value(self, value, dialect):
"""Data going out from the database will be explicitly casted to the
``ObjectID``.
"""
if value is None:
return None

return ObjectID(value)
return None if value is None else ObjectID(value)
Comment on lines -63 to +60
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ObjectIDType.process_result_value refactored with the following changes:



class MyBase(BaseMixins, sa.orm.DeclarativeBase):
Expand Down
14 changes: 4 additions & 10 deletions src/quart_sqlalchemy/sim/handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,11 @@ def update_app_name_by_id(self, session: sa.orm.Session, magic_client_id, app_na
"""
client = self.logic.MagicClient.update_by_id(session, magic_client_id, app_name=app_name)

if not client:
return None

return client.app_name
return client.app_name if client else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function MagicClientHandler.update_app_name_by_id refactored with the following changes:


@provide_global_contextual_session
def update_by_id(self, session: sa.orm.Session, magic_client_id, **kwargs):
client = self.logic.MagicClient.update_by_id(session, magic_client_id, **kwargs)

return client
return self.logic.MagicClient.update_by_id(session, magic_client_id, **kwargs)
Comment on lines -109 to +106
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function MagicClientHandler.update_by_id refactored with the following changes:


@provide_global_contextual_session
def set_inactive_by_id(self, session: sa.orm.Session, magic_client_id):
Expand Down Expand Up @@ -341,11 +336,10 @@ def sync_auth_wallet(
wallet_type: t.Optional[WalletType] = None,
):
with session.begin_nested():
existing_wallet = self.logic.AuthWallet.get_by_auth_user_id(
if existing_wallet := self.logic.AuthWallet.get_by_auth_user_id(
session,
auth_user_id,
)
if existing_wallet:
):
Comment on lines -344 to +342
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthWalletHandler.sync_auth_wallet refactored with the following changes:

raise RuntimeError("WalletExistsForNetworkAndWalletType")

return self.logic.AuthWallet.add(
Expand Down
37 changes: 11 additions & 26 deletions src/quart_sqlalchemy/sim/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ class LogicMeta(type):
def __init__(cls, name, bases, cls_dict):
if not hasattr(cls, "_registry"):
cls._registry = {}
else:
if cls.__name__ not in cls._ignore:
model = getattr(cls, "model", None)
if model is not None:
name = model.__name__
elif cls.__name__ not in cls._ignore:
model = getattr(cls, "model", None)
if model is not None:
name = model.__name__

cls._registry[name] = cls()
cls._registry[name] = cls()
Comment on lines -34 to +39
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LogicMeta.__init__ refactored with the following changes:


super().__init__(name, bases, cls_dict)

Expand Down Expand Up @@ -161,10 +160,7 @@ def add_by_email_and_client_id(
user_type=user_type,
):
logger.exception(
"User duplication for email: {} (client_id: {})".format(
email,
client_id,
),
f"User duplication for email: {email} (client_id: {client_id})"
Comment on lines -164 to +163
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthUser.add_by_email_and_client_id refactored with the following changes:

)
raise DuplicateAuthUser()

Expand All @@ -176,10 +172,7 @@ def add_by_email_and_client_id(
**kwargs,
)
logger.info(
"New auth user (id: {}) created by email (client_id: {})".format(
row.id,
client_id,
),
f"New auth user (id: {row.id}) created by email (client_id: {client_id})"
)

return row
Expand All @@ -203,7 +196,7 @@ def add_by_client_id(
date_verified=datetime.utcnow() if is_verified else None,
)
logger.info(
"New auth user (id: {}) created by (client_id: {})".format(row.id, client_id),
f"New auth user (id: {row.id}) created by (client_id: {client_id})"
Comment on lines -206 to +199
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthUser.add_by_client_id refactored with the following changes:

)

return row
Expand Down Expand Up @@ -409,7 +402,7 @@ def add(
management_type=None,
auth_user_id=None,
):
new_row = self._repository.add(
return self._repository.add(
Comment on lines -412 to +405
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthWallet.add refactored with the following changes:

session,
auth_user_id=auth_user_id,
public_address=public_address,
Expand All @@ -419,8 +412,6 @@ def add(
network=network,
)

return new_row

@provide_global_contextual_session
def get_by_id(self, session, model_id, allow_inactive=False, join_list=None):
return self._repository.get_by_id(
Expand All @@ -441,10 +432,7 @@ def get_by_public_address(self, session, public_address, network=None, is_active

row = self._repository.get_by(session, filters=filters, allow_inactive=not is_active)

if not row:
return None

return one(row)
return one(row) if row else None
Comment on lines -444 to +435
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthWallet.get_by_public_address refactored with the following changes:


@provide_global_contextual_session
def get_by_auth_user_id(
Expand All @@ -470,10 +458,7 @@ def get_by_auth_user_id(
session, filters=filters, join_list=join_list, allow_inactive=not is_active
)

if not rows:
return []

return rows
return rows or []
Comment on lines -473 to +461
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthWallet.get_by_auth_user_id refactored with the following changes:


@provide_global_contextual_session
def update_by_id(self, session, model_id, **kwargs):
Expand Down
31 changes: 10 additions & 21 deletions src/quart_sqlalchemy/sim/repo_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ def get_by(

join_list = join_list or ()

if order_by_clause is not None:
order_by_clause = (order_by_clause,)
else:
order_by_clause = ()

order_by_clause = (order_by_clause, ) if order_by_clause is not None else ()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function RepositoryLegacyAdapter.get_by refactored with the following changes:

return self._adapted.select(
session,
conditions=filters,
Expand Down Expand Up @@ -129,9 +125,7 @@ def count_by(
else:
selectables = [sa.label("count", sa.func.count(self.model.id))]

for group in group_by:
selectables.append(group.expression)

selectables.extend(group.expression for group in group_by)
Comment on lines -132 to +128
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function RepositoryLegacyAdapter.count_by refactored with the following changes:

result = self._adapted.select(session, selectables, conditions=filters, group_by=group_by)

return result.all()
Expand Down Expand Up @@ -178,15 +172,16 @@ def yield_by_chunk(
):
filters = filters or ()
join_list = join_list or ()
results = self._adapted.select(
yield from self._adapted.select(
session,
conditions=filters,
options=[sa.orm.selectinload(getattr(self.model, attr)) for attr in join_list],
options=[
sa.orm.selectinload(getattr(self.model, attr))
for attr in join_list
],
include_inactive=allow_inactive,
yield_by_chunk=chunk_size,
)
for result in results:
yield result
Comment on lines -181 to -189
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function RepositoryLegacyAdapter.yield_by_chunk refactored with the following changes:



class PydanticScalarResult(sa.ScalarResult, t.Generic[ModelSchemaT]):
Expand Down Expand Up @@ -243,9 +238,7 @@ def insert(
create_data = create_schema.dict()
result = super().insert(session, create_data)

if sqla_model:
return result
return self.model_schema.from_orm(result)
return result if sqla_model else self.model_schema.from_orm(result)
Comment on lines -246 to +241
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function insert refactored with the following changes:


def update(
self,
Expand All @@ -266,9 +259,7 @@ def update(
session.flush()
session.refresh(existing)

if sqla_model:
return existing
return self.model_schema.from_orm(existing)
return existing if sqla_model else self.model_schema.from_orm(existing)
Comment on lines -269 to +262
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function update refactored with the following changes:


def get(
self,
Expand All @@ -291,9 +282,7 @@ def get(
if row is None:
return

if sqla_model:
return row
return self.model_schema.from_orm(row)
return row if sqla_model else self.model_schema.from_orm(row)
Comment on lines -294 to +285
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get refactored with the following changes:


def select(
self,
Expand Down
5 changes: 1 addition & 4 deletions src/quart_sqlalchemy/sim/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,7 @@ class Config:

@validator("status")
def set_status_by_error_code(cls, v, values):
error_code = values.get("error_code")
if error_code:
return "failed"
return "ok"
return "failed" if (error_code := values.get("error_code")) else "ok"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ResponseWrapper.set_status_by_error_code refactored with the following changes:



class MagicClientSchema(BaseSchema):
Expand Down
7 changes: 2 additions & 5 deletions src/quart_sqlalchemy/sim/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __lt__(self, other):
return False

def __hash__(self):
return hash(tuple([self._encoded_id, self._decoded_id]))
return hash((self._encoded_id, self._decoded_id))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ObjectID.__hash__ refactored with the following changes:


def __str__(self):
return "{encoded_id}".format(encoded_id=self._encoded_id)
Expand All @@ -88,10 +88,7 @@ def encode(self):
return self._encoded_id

def _decode(self, value):
if isinstance(value, int):
return value
else:
return self.hashids.decode(value)[0]
return value if isinstance(value, int) else self.hashids.decode(value)[0]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ObjectID._decode refactored with the following changes:


def decode(self):
return self._decoded_id
Expand Down
Loading