Skip to content

PYTHON-4121: lint + format on backend #19

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

Merged
merged 1 commit into from
Jan 10, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,9 @@ async def update_user(
Update user.
"""
if current_user.hashed_password:
user = await crud.user.authenticate(
db, email=current_user.email, password=obj_in.original
)
user = await crud.user.authenticate(db, email=current_user.email, password=obj_in.original)
if not obj_in.original or not user:
raise HTTPException(
status_code=400, detail="Unable to authenticate this update."
)
raise HTTPException(status_code=400, detail="Unable to authenticate this update.")
current_user_data = jsonable_encoder(current_user)
user_in = schemas.UserUpdate(**current_user_data)
if obj_in.password is not None:
Expand Down Expand Up @@ -150,9 +146,7 @@ async def create_user(
)
user = await crud.user.create(db, obj_in=user_in)
if settings.EMAILS_ENABLED and user_in.email:
send_new_account_email(
email_to=user_in.email, username=user_in.email, password=user_in.password
)
send_new_account_email(email_to=user_in.email, username=user_in.email, password=user_in.password)
return user


Expand Down
8 changes: 2 additions & 6 deletions {{cookiecutter.project_slug}}/backend/app/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ async def get_current_user(
return user


async def get_totp_user(
db: AgnosticDatabase = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
async def get_totp_user(db: AgnosticDatabase = Depends(get_db), token: str = Depends(reusable_oauth2)) -> models.User:
token_data = get_token_payload(token)
if token_data.refresh or not token_data.totp:
# Refresh token is not a valid access token and TOTP False cannot be used to validate TOTP
Expand Down Expand Up @@ -115,9 +113,7 @@ async def get_current_active_superuser(
current_user: models.User = Depends(get_current_user),
) -> models.User:
if not crud.user.is_superuser(current_user):
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
raise HTTPException(status_code=400, detail="The user doesn't have enough privileges")
return current_user


Expand Down
6 changes: 1 addition & 5 deletions {{cookiecutter.project_slug}}/backend/app/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,7 @@ def get_project_name(cls, v: Optional[str], info: ValidationInfo) -> str:

@field_validator("EMAILS_ENABLED", mode="before")
def get_emails_enabled(cls, v: bool, info: ValidationInfo) -> bool:
return bool(
info.data.get("SMTP_HOST")
and info.data.get("SMTP_PORT")
and info.data.get("EMAILS_FROM_EMAIL")
)
return bool(info.data.get("SMTP_HOST") and info.data.get("SMTP_PORT") and info.data.get("EMAILS_FROM_EMAIL"))

EMAIL_TEST_USER: EmailStr = "test@example.com" # type: ignore
FIRST_SUPERUSER: EmailStr
Expand Down
7 changes: 3 additions & 4 deletions {{cookiecutter.project_slug}}/backend/app/app/db/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,18 @@ def __new__(cls):
cls.instance.mongo_client = motor_asyncio.AsyncIOMotorClient(
settings.MONGO_DATABASE_URI, driver=DRIVER_INFO
)
cls.instance.engine = AIOEngine(
client=cls.instance.mongo_client,
database=settings.MONGO_DATABASE
)
cls.instance.engine = AIOEngine(client=cls.instance.mongo_client, database=settings.MONGO_DATABASE)
return cls.instance


def MongoDatabase() -> core.AgnosticDatabase:
return _MongoClientSingleton().mongo_client[settings.MONGO_DATABASE]


def get_engine() -> AIOEngine:
return _MongoClientSingleton().engine


async def ping():
await MongoDatabase().command("ping")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@
# Consider reworking to consolidate information to a userId. This may not work well
class Token(Base):
token: str
authenticates_id: User = Reference()
authenticates_id: User = Reference()
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
class BaseSchema(BaseModel):
@property
def as_db_dict(self):
to_db = self.model_dump(
exclude_defaults=True, exclude_none=True, exclude={"identifier, id"}
)
to_db = self.model_dump(exclude_defaults=True, exclude_none=True, exclude={"identifier, id"})
for key in ["id", "identifier"]:
if key in self.model_dump().keys():
to_db[key] = self.model_dump()[key].hex
Expand All @@ -23,16 +21,12 @@ def as_db_dict(self):
class MetadataBaseSchema(BaseSchema):
# Receive via API
# https://www.dublincore.org/specifications/dublin-core/dcmi-terms/#section-3
title: Optional[str] = Field(
None, description="A human-readable title given to the resource."
)
title: Optional[str] = Field(None, description="A human-readable title given to the resource.")
description: Optional[str] = Field(
None,
description="A short description of the resource.",
)
isActive: Optional[bool] = Field(
default=True, description="Whether the resource is still actively maintained."
)
isActive: Optional[bool] = Field(default=True, description="Whether the resource is still actively maintained.")
isPrivate: Optional[bool] = Field(
default=True,
description="Whether the resource is private to team members with appropriate authorisation.",
Expand All @@ -44,22 +38,14 @@ class MetadataBaseCreate(MetadataBaseSchema):


class MetadataBaseUpdate(MetadataBaseSchema):
identifier: UUID = Field(
..., description="Automatically generated unique identity for the resource."
)
identifier: UUID = Field(..., description="Automatically generated unique identity for the resource.")


class MetadataBaseInDBBase(MetadataBaseSchema):
# Identifier managed programmatically
identifier: UUID = Field(
..., description="Automatically generated unique identity for the resource."
)
created: date = Field(
..., description="Automatically generated date resource was created."
)
isActive: bool = Field(
..., description="Whether the resource is still actively maintained."
)
identifier: UUID = Field(..., description="Automatically generated unique identity for the resource.")
created: date = Field(..., description="Automatically generated date resource was created.")
isActive: bool = Field(..., description="Whether the resource is still actively maintained.")
isPrivate: bool = Field(
...,
description="Whether the resource is private to team members with appropriate authorisation.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@


@pytest.mark.asyncio
async def test_get_users_superuser_me(
client: TestClient, superuser_token_headers: Dict[str, str]
) -> None:
async def test_get_users_superuser_me(client: TestClient, superuser_token_headers: Dict[str, str]) -> None:
r = client.get(f"{settings.API_V1_STR}/users/", headers=superuser_token_headers)
current_user = r.json()
assert current_user
Expand All @@ -23,9 +21,7 @@ async def test_get_users_superuser_me(


@pytest.mark.asyncio
async def test_get_users_normal_user_me(
client: TestClient, normal_user_token_headers: Dict[str, str]
) -> None:
async def test_get_users_normal_user_me(client: TestClient, normal_user_token_headers: Dict[str, str]) -> None:
r = client.get(f"{settings.API_V1_STR}/users/", headers=normal_user_token_headers)
current_user = r.json()
assert current_user
Expand All @@ -35,9 +31,7 @@ async def test_get_users_normal_user_me(


@pytest.mark.asyncio
async def test_create_user_new_email(
client: TestClient, superuser_token_headers: dict, db: AgnosticDatabase
) -> None:
async def test_create_user_new_email(client: TestClient, superuser_token_headers: dict, db: AgnosticDatabase) -> None:
username = random_email()
password = random_lower_string()
data = {"email": username, "password": password}
Expand Down Expand Up @@ -74,9 +68,7 @@ async def test_create_user_existing_username(


@pytest.mark.asyncio
async def test_retrieve_users(
client: TestClient, superuser_token_headers: dict, db: AgnosticDatabase
) -> None:
async def test_retrieve_users(client: TestClient, superuser_token_headers: dict, db: AgnosticDatabase) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,5 @@ def superuser_token_headers(client: TestClient) -> Dict[str, str]:


@pytest_asyncio.fixture(scope="module")
async def normal_user_token_headers(
client: TestClient, db: AgnosticDatabase
) -> Dict[str, str]:
return await authentication_token_from_email(
client=client, email=settings.EMAIL_TEST_USER, db=db
)
async def normal_user_token_headers(client: TestClient, db: AgnosticDatabase) -> Dict[str, str]:
return await authentication_token_from_email(client=client, email=settings.EMAIL_TEST_USER, db=db)
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ async def test_authenticate_user(db: AgnosticDatabase) -> None:
password = random_lower_string()
user_in = UserCreate(email=email, password=password)
user = await crud.user.create(db, obj_in=user_in)
authenticated_user = await crud.user.authenticate(
db, email=email, password=password
)
authenticated_user = await crud.user.authenticate(db, email=email, password=password)
assert authenticated_user
assert user.email == authenticated_user.email

Expand Down Expand Up @@ -103,6 +101,4 @@ async def test_update_user(db: AgnosticDatabase) -> None:
user_2 = await crud.user.get(db, id=user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(
plain_password=new_password, hashed_password=user_2.hashed_password
)
assert verify_password(plain_password=new_password, hashed_password=user_2.hashed_password)
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
from app.tests.utils.utils import random_email, random_lower_string


def user_authentication_headers(
*, client: TestClient, email: str, password: str
) -> Dict[str, str]:
def user_authentication_headers(*, client: TestClient, email: str, password: str) -> Dict[str, str]:
data = {"username": email, "password": password}

r = client.post(f"{settings.API_V1_STR}/login/oauth", data=data)
Expand All @@ -22,9 +20,7 @@ def user_authentication_headers(
return headers


async def authentication_token_from_email(
*, client: TestClient, email: str, db: AgnosticDatabase
) -> Dict[str, str]:
async def authentication_token_from_email(*, client: TestClient, email: str, db: AgnosticDatabase) -> Dict[str, str]:
"""
Return a valid token for the user with given email.

Expand Down