Skip to content

Commit

Permalink
Refactor patch_single function and update its corresponding test (#275)
Browse files Browse the repository at this point in the history
  • Loading branch information
jrycw authored Mar 21, 2024
1 parent 3306d3a commit 2df940d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 56 deletions.
88 changes: 35 additions & 53 deletions piccolo_api/crud/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1154,61 +1154,43 @@ async def patch_single(

cls = self.table

if issubclass(cls, BaseUser):
values = {
getattr(cls, key): getattr(model, key)
for key in cleaned_data.keys()
}
if values["password"]:
cls._validate_password(values["password"])
values["password"] = cls.hash_password(values["password"])
else:
values.pop("password")

await cls.update(values).where(cls.email == values["email"]).run()
return Response(status_code=200)
else:
try:
values = {
getattr(cls, key): getattr(model, key)
for key in data.keys()
}
except AttributeError:
unrecognised_keys = set(data.keys()) - set(
model.model_dump().keys()
)
return Response(
f"Unrecognised keys - {unrecognised_keys}.",
status_code=400,
)
try:
values = {getattr(cls, key): getattr(model, key) for key in data.keys()}
except AttributeError:
unrecognised_keys = set(data.keys()) - set(model.model_dump().keys())
return Response(
f"Unrecognised keys - {unrecognised_keys}.",
status_code=400,
)

if self._hook_map:
values = await execute_patch_hooks(
hooks=self._hook_map,
hook_type=HookType.pre_patch,
row_id=row_id,
values=values,
request=request,
)
if self._hook_map:
values = await execute_patch_hooks(
hooks=self._hook_map,
hook_type=HookType.pre_patch,
row_id=row_id,
values=values,
request=request,
)

try:
await cls.update(values).where(
cls._meta.primary_key == row_id
).run()
new_row = (
await cls.select(exclude_secrets=self.exclude_secrets)
.where(cls._meta.primary_key == row_id)
.first()
.run()
)
assert new_row
return CustomJSONResponse(
self.pydantic_model(**new_row).model_dump_json()
)
except ValueError:
return Response(
"Unable to save the resource.", status_code=500
)
if issubclass(cls, BaseUser):
if password := values.pop("password", None):
try:
cls._validate_password(password)
except ValueError as e:
return Response(f"{e}", status_code=400)
values["password"] = cls.hash_password(password)
try:
await cls.update(values).where(cls._meta.primary_key == row_id).run()
new_row = (
await cls.select(exclude_secrets=self.exclude_secrets)
.where(cls._meta.primary_key == row_id)
.first()
.run()
)
assert new_row
return CustomJSONResponse(self.pydantic_model(**new_row).model_dump_json())
except ValueError:
return Response("Unable to save the resource.", status_code=500)

@apply_validators
@db_exception_handler
Expand Down
6 changes: 3 additions & 3 deletions tests/crud/test_crud_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,9 @@ def test_patch_user_fails(self):
"superuser": False,
}

with self.assertRaises(ValueError):
response = client.patch(f"/{user['id']}/", json=json)
self.assertEqual(response.content, b"The password is too short.")
response = client.patch(f"/{user['id']}/", json=json)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content, b"The password is too short.")

def test_patch_fails(self):
"""
Expand Down

0 comments on commit 2df940d

Please sign in to comment.