Skip to content

Commit

Permalink
api.helpers patch (#36)
Browse files Browse the repository at this point in the history
* Remove api.helpers.is_digit()

* Use str.partition for parsing sanitizing filter keys

* Fix is_valid_base64() parameter docs

* Use const suffixes in api.helpers.sanitize_filter_key()
  • Loading branch information
bswck authored Jun 14, 2023
1 parent 3d473a0 commit 3c19a11
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 28 deletions.
26 changes: 6 additions & 20 deletions fastadmin/api/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ def sanitize_filter_key(key: str, fields: list[ModelFieldWidgetSchema]) -> tuple
:return: A tuple of sanitized key and condition.
"""
if "__" not in key:
key = f"{key}__exact"
field_name = key.split("__", 1)[0]
condition = key.split("__", 1)[1]
key += "__exact"
field_name, _, condition = key.partition("__")
field: ModelFieldWidgetSchema | None = next((field for field in fields if field.name == field_name), None)
if field and field.filter_widget_props.get("parentModel") and not field.is_m2m:
field_name = f"{field_name}_id"
field_name += "_id"
return field_name, condition


Expand All @@ -52,32 +51,19 @@ def is_valid_uuid(uuid_to_test: str) -> bool:
return str(uuid_obj) == uuid_to_test


def is_digit(digit_to_test: str) -> bool:
"""Check if digit_to_test is a digit.
:param digit_to_test: A digit to test.
:return: True if digit_to_test is a digit, False otherwise.
"""
try:
int(digit_to_test)
except ValueError:
return False
return True


def is_valid_id(id: UUID | int) -> bool:
"""Check if id is a valid id.
:param id: An id to test.
:return: True if id is a valid id, False otherwise.
"""
return is_digit(str(id)) or is_valid_uuid(str(id))
return str(id).isdigit() or is_valid_uuid(str(id))


def is_valid_base64(value: str) -> bool:
"""Check if s is a valid base64.
"""Check if a string is a valid base64.
:param s: A string to test.
:param value: A string to test.
:return: True if s is a valid base64, False otherwise.
"""
try:
Expand Down
9 changes: 1 addition & 8 deletions tests/api/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import jwt

from fastadmin.api.helpers import is_digit, is_valid_id, is_valid_uuid, sanitize_filter_value
from fastadmin.api.helpers import is_valid_id, is_valid_uuid, sanitize_filter_value
from fastadmin.api.service import get_user_id_from_session_id
from fastadmin.settings import settings

Expand All @@ -23,13 +23,6 @@ async def test_is_valid_uuid():
assert is_valid_uuid("invalid") is False


async def test_is_digit():
assert is_digit("true") is False
assert is_digit("0.2") is False
assert is_digit("-1") is True
assert is_digit("foo") is False


async def test_is_valid_id():
assert is_valid_id(1) is True
assert is_valid_uuid(str(uuid.uuid1())) is True
Expand Down

0 comments on commit 3c19a11

Please sign in to comment.