muffin-rest 9.4.0__tar.gz → 10.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/PKG-INFO +3 -3
  2. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/handler.py +15 -14
  3. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/limits.py +15 -11
  4. muffin_rest-10.1.0/muffin_rest/marshmallow.py +20 -0
  5. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/options.py +1 -16
  6. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/utils.py +2 -1
  7. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/pyproject.toml +4 -4
  8. muffin_rest-9.4.0/muffin_rest/marshmallow.py +0 -26
  9. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/LICENSE +0 -0
  10. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/README.rst +0 -0
  11. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/__init__.py +0 -0
  12. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/api.py +0 -0
  13. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/errors.py +0 -0
  14. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/filters.py +0 -0
  15. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/mongo/__init__.py +0 -0
  16. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/mongo/filters.py +0 -0
  17. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/mongo/schema.py +0 -0
  18. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/mongo/sorting.py +0 -0
  19. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/mongo/types.py +0 -0
  20. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/mongo/utils.py +0 -0
  21. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/openapi.py +0 -0
  22. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/__init__.py +0 -0
  23. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/filters.py +0 -0
  24. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/handler.py +0 -0
  25. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/openapi.py +0 -0
  26. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/options.py +0 -0
  27. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/schemas.py +0 -0
  28. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/sorting.py +0 -0
  29. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/peewee/types.py +0 -0
  30. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/py.typed +0 -0
  31. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/redoc.html +0 -0
  32. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/schemas.py +0 -0
  33. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/sorting.py +0 -0
  34. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/sqlalchemy/__init__.py +0 -0
  35. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/sqlalchemy/filters.py +0 -0
  36. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/sqlalchemy/sorting.py +0 -0
  37. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/sqlalchemy/types.py +0 -0
  38. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/swagger.html +0 -0
  39. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/types.py +0 -0
  40. {muffin_rest-9.4.0 → muffin_rest-10.1.0}/muffin_rest/utils.py +0 -0
@@ -1,8 +1,7 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.3
2
2
  Name: muffin-rest
3
- Version: 9.4.0
3
+ Version: 10.1.0
4
4
  Summary: The package provides enhanced support for writing REST APIs with Muffin framework
5
- Home-page: https://github.com/klen/muffin-rest
6
5
  License: MIT
7
6
  Keywords: rest,api,muffin,asgi,asyncio,trio
8
7
  Author: Kirill Klenov
@@ -33,6 +32,7 @@ Requires-Dist: muffin-databases ; extra == "sqlalchemy"
33
32
  Requires-Dist: muffin-peewee-aio ; extra == "peewee"
34
33
  Requires-Dist: pyyaml ; extra == "yaml"
35
34
  Requires-Dist: sqlalchemy ; extra == "sqlalchemy"
35
+ Project-URL: Homepage, https://github.com/klen/muffin-rest
36
36
  Project-URL: Repository, https://github.com/klen/muffin-rest
37
37
  Description-Content-Type: text/x-rst
38
38
 
@@ -1,4 +1,5 @@
1
1
  """Base class for API REST Handlers."""
2
+
2
3
  import abc
3
4
  import inspect
4
5
  from typing import (
@@ -7,6 +8,7 @@ from typing import (
7
8
  Generic,
8
9
  Iterable,
9
10
  Literal,
11
+ Mapping,
10
12
  Optional,
11
13
  Sequence,
12
14
  Union,
@@ -97,8 +99,6 @@ class RESTBase(Generic[TVResource], Handler, metaclass=RESTHandlerMeta):
97
99
  self.auth = await self.authorize(request)
98
100
 
99
101
  meta = self.meta
100
- if meta.rate_limit:
101
- await self.rate_limit(request)
102
102
 
103
103
  self.collection = await self.prepare_collection(request)
104
104
  resource = await self.prepare_resource(request)
@@ -142,11 +142,6 @@ class RESTBase(Generic[TVResource], Handler, metaclass=RESTHandlerMeta):
142
142
  raise APIError.UNAUTHORIZED()
143
143
  return auth
144
144
 
145
- async def rate_limit(self, request: Request):
146
- """Default rate limit method. Proxy rate limit to self.api."""
147
- if not await self.meta.rate_limiter.check(f"{self.auth}"):
148
- raise APIError.TOO_MANY_REQUESTS()
149
-
150
145
  # Prepare data
151
146
  # ------------
152
147
  @abc.abstractmethod
@@ -228,24 +223,30 @@ class RESTBase(Generic[TVResource], Handler, metaclass=RESTHandlerMeta):
228
223
  schema_options.setdefault("exclude", query.get("schema_exclude", ()))
229
224
  return self.meta.Schema(**schema_options)
230
225
 
226
+ async def load_data(self, request: Request):
227
+ """Load data from request and create/update a resource."""
228
+ try:
229
+ data = await request.data(raise_errors=True)
230
+ except (ValueError, TypeError) as err:
231
+ raise APIError.BAD_REQUEST(str(err)) from err
232
+
233
+ return data
234
+
231
235
  async def load(
232
236
  self, request: Request, resource: Optional[TVResource] = None, **schema_options
233
237
  ) -> TVData[TVResource]:
234
238
  """Load data from request and create/update a resource."""
235
239
  schema = self.get_schema(request, resource=resource, **schema_options)
236
- return cast(
237
- TVData[TVResource], await load_data(request, schema, partial=resource is not None)
238
- )
240
+ data = cast(Union[Mapping, list], await self.load_data(request))
241
+ return cast(TVData[TVResource], await load_data(data, schema, partial=resource is not None))
239
242
 
240
243
  @overload
241
244
  async def dump( # type: ignore[misc]
242
245
  self, request, data: TVData, *, many: Literal[True]
243
- ) -> list[TSchemaRes]:
244
- ...
246
+ ) -> list[TSchemaRes]: ...
245
247
 
246
248
  @overload
247
- async def dump(self, request, data: TVData, *, many: bool = False) -> TSchemaRes:
248
- ...
249
+ async def dump(self, request, data: TVData, *, many: bool = False) -> TSchemaRes: ...
249
250
 
250
251
  async def dump(
251
252
  self,
@@ -1,11 +1,12 @@
1
1
  import abc
2
2
  from time import time
3
+ from typing import Any
3
4
 
4
5
 
5
6
  class RateLimiter(abc.ABC):
6
7
  """Rate limiter."""
7
8
 
8
- def __init__(self, limit: int, period: int, **opts):
9
+ def __init__(self, limit: int, *, period: int = 60, **opts):
9
10
  """Initialize the rate limiter.
10
11
 
11
12
  Args:
@@ -21,26 +22,29 @@ class RateLimiter(abc.ABC):
21
22
  raise NotImplementedError
22
23
 
23
24
 
24
- RATE_LIMITS = {}
25
-
26
-
27
25
  class MemoryRateLimiter(RateLimiter):
28
26
  """Memory rate limiter. Do not use in production."""
29
27
 
28
+ def __init__(self, limit: int, **opts):
29
+ super().__init__(limit, **opts)
30
+ self.storage: dict[Any, tuple[float, int]] = {}
31
+
30
32
  async def check(self, key: str) -> bool:
31
33
  """Check the request."""
32
34
  now = time()
33
- if key not in RATE_LIMITS:
34
- RATE_LIMITS[key] = (now, 1)
35
+ storage = self.storage
36
+
37
+ if key not in storage:
38
+ storage[key] = (now, 1)
35
39
  return True
36
40
 
37
- last, count = RATE_LIMITS[key]
41
+ last, count = storage[key]
38
42
  if now - last > self.period:
39
- RATE_LIMITS[key] = (now, 1)
43
+ storage[key] = (now, 1)
40
44
  return True
41
45
 
42
46
  if count < self.limit:
43
- RATE_LIMITS[key] = (last, count + 1)
47
+ storage[key] = (last, count + 1)
44
48
  return True
45
49
 
46
50
  return False
@@ -51,7 +55,7 @@ class RedisRateLimiter(RateLimiter):
51
55
 
52
56
  # TODO: Asyncio lock
53
57
 
54
- def __init__(self, limit: int, period: int, *, redis, **opts):
58
+ def __init__(self, limit: int, *, redis, **opts):
55
59
  """Initialize the rate limiter.
56
60
 
57
61
  Args:
@@ -59,7 +63,7 @@ class RedisRateLimiter(RateLimiter):
59
63
  period (int): The period of time in seconds.
60
64
  redis (aioredis.Redis): The Redis connection.
61
65
  """
62
- super().__init__(limit, period)
66
+ super().__init__(limit, **opts)
63
67
  self.redis = redis
64
68
 
65
69
  async def check(self, key: str) -> bool:
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Optional, Union
4
+
5
+ from marshmallow import Schema, ValidationError
6
+
7
+ from muffin_rest.errors import APIError
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Mapping
11
+
12
+
13
+ async def load_data(data: Union[Mapping, list], schema: Optional[Schema] = None, **params):
14
+ if schema is None:
15
+ return data
16
+
17
+ try:
18
+ return schema.load(data, many=isinstance(data, list), **params)
19
+ except ValidationError as err:
20
+ raise APIError.BAD_REQUEST("Bad request data", errors=err.messages) from err
@@ -1,11 +1,9 @@
1
1
  """REST Options."""
2
2
 
3
- from typing import Any, ClassVar
3
+ from typing import ClassVar
4
4
 
5
5
  import marshmallow as ma
6
6
 
7
- from muffin_rest.limits import MemoryRateLimiter, RateLimiter
8
-
9
7
  from .filters import Filters
10
8
  from .sorting import Sorting
11
9
 
@@ -53,14 +51,6 @@ class RESTOptions:
53
51
  schema_meta: ClassVar[dict] = {}
54
52
  schema_unknown: str = ma.EXCLUDE
55
53
 
56
- # Rate Limiting
57
- # -------------
58
-
59
- rate_limit: int = 0
60
- rate_limit_period: int = 60
61
- rate_limit_cls: type[RateLimiter] = MemoryRateLimiter
62
- rate_limit_cls_opts: ClassVar[dict[str, Any]] = {}
63
-
64
54
  def __init__(self, cls):
65
55
  """Inherit meta options."""
66
56
  for base in reversed(cls.mro()):
@@ -86,11 +76,6 @@ class RESTOptions:
86
76
  if not self.limit_max:
87
77
  self.limit_max = self.limit
88
78
 
89
- if self.rate_limit:
90
- self.rate_limiter = self.rate_limit_cls(
91
- self.rate_limit, self.rate_limit_period, **self.rate_limit_cls_opts
92
- )
93
-
94
79
  def setup_schema_meta(self, _):
95
80
  """Generate meta for schemas."""
96
81
  return type(
@@ -1,4 +1,5 @@
1
1
  """Support filters for Peewee ORM."""
2
+
2
3
  from __future__ import annotations
3
4
 
4
5
  from typing import TYPE_CHECKING, Optional
@@ -8,7 +9,7 @@ if TYPE_CHECKING:
8
9
  from peewee import Field
9
10
 
10
11
 
11
- def get_model_field_by_name(handler, name: str, stacklevel=5) -> Optional[Field]:
12
+ def get_model_field_by_name(handler, name: str, *, stacklevel=5) -> Optional[Field]:
12
13
  """Get model field by name."""
13
14
  fields = handler.meta.model._meta.fields
14
15
  candidate = fields.get(name)
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "muffin-rest"
3
- version = "9.4.0"
3
+ version = "10.1.0"
4
4
  description = "The package provides enhanced support for writing REST APIs with Muffin framework"
5
5
  readme = "README.rst"
6
6
  homepage = "https://github.com/klen/muffin-rest"
@@ -78,7 +78,7 @@ ignore_missing_imports = true
78
78
  [tool.tox]
79
79
  legacy_tox_ini = """
80
80
  [tox]
81
- envlist = py39,py310,py311,py312,py313,pypy39
81
+ envlist = py310,py311,py312,py313,pypy39
82
82
 
83
83
  [testenv]
84
84
  deps = -e .[tests]
@@ -88,7 +88,7 @@ commands =
88
88
 
89
89
  [tool.ruff]
90
90
  line-length = 100
91
- target-version = "py39"
91
+ target-version = "py310"
92
92
  exclude = [".venv", "docs", "examples"]
93
93
 
94
94
  [tool.ruff.lint]
@@ -117,7 +117,7 @@ ignore = [
117
117
 
118
118
  [tool.black]
119
119
  line-length = 100
120
- target-version = ["py39", "py310", "py311", "py312", "py313"]
120
+ target-version = ["py310", "py311", "py312", "py313"]
121
121
  preview = true
122
122
 
123
123
  [build-system]
@@ -1,26 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from collections.abc import Mapping
4
- from typing import TYPE_CHECKING, Optional, Union, cast
5
-
6
- from marshmallow import Schema, ValidationError
7
-
8
- from muffin_rest.errors import APIError
9
-
10
- if TYPE_CHECKING:
11
- from asgi_tools import Request
12
-
13
-
14
- async def load_data(request: Request, schema: Optional[Schema] = None, **params):
15
- try:
16
- data = await request.data(raise_errors=True)
17
- except (ValueError, TypeError) as err:
18
- raise APIError.BAD_REQUEST(str(err)) from err
19
-
20
- if schema is None:
21
- return data
22
-
23
- try:
24
- return schema.load(cast(Union[Mapping, list], data), many=isinstance(data, list), **params)
25
- except ValidationError as err:
26
- raise APIError.BAD_REQUEST("Bad request data", errors=err.messages) from err
File without changes
File without changes