imgproxykit 0.4.0__tar.gz → 0.5.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 (81) hide show
  1. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/PKG-INFO +35 -15
  2. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/README.md +30 -14
  3. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/client.py +79 -31
  4. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/settings.py +11 -5
  5. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/shortcuts.py +0 -2
  6. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/sources.py +0 -2
  7. imgproxykit-0.5.0/imgproxykit/integrations/drf/__init__.py +16 -0
  8. imgproxykit-0.5.0/imgproxykit/integrations/drf/serializers.py +117 -0
  9. imgproxykit-0.5.0/imgproxykit/internal/encoding.py +31 -0
  10. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/auto_rotate.py +2 -3
  11. imgproxykit-0.5.0/imgproxykit/options/background.py +67 -0
  12. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/base.py +12 -7
  13. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/blur.py +2 -3
  14. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/cache_buster.py +3 -3
  15. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/crop.py +18 -15
  16. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/dpr.py +1 -3
  17. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/enforce_thumbnail.py +2 -3
  18. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/enlarge.py +2 -3
  19. imgproxykit-0.5.0/imgproxykit/options/expires.py +57 -0
  20. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/extend.py +18 -14
  21. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/extend_aspect_ratio.py +18 -14
  22. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/filename.py +3 -3
  23. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/flip.py +3 -3
  24. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/format.py +3 -6
  25. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/format_quality.py +3 -3
  26. imgproxykit-0.5.0/imgproxykit/options/gravity.py +152 -0
  27. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/height.py +2 -3
  28. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/keep_copyright.py +2 -3
  29. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/max_animation_frame_resolution.py +2 -3
  30. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/max_animation_frames.py +2 -3
  31. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/max_bytes.py +2 -3
  32. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/max_result_dimension.py +2 -3
  33. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/max_src_file_size.py +2 -3
  34. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/max_src_resolution.py +2 -3
  35. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/min_height.py +2 -3
  36. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/min_width.py +2 -3
  37. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/padding.py +21 -5
  38. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/pixelate.py +2 -3
  39. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/preserve_hdr.py +2 -3
  40. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/preset.py +5 -5
  41. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/quality.py +2 -6
  42. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/raw.py +1 -3
  43. imgproxykit-0.5.0/imgproxykit/options/resize.py +149 -0
  44. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/resizing_type.py +3 -3
  45. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/return_attachment.py +2 -3
  46. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/rotate.py +2 -3
  47. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/sharpen.py +2 -3
  48. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/size.py +3 -3
  49. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/skip_processing.py +3 -3
  50. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/strip_color_profile.py +2 -3
  51. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/strip_metadata.py +2 -3
  52. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/trim.py +32 -6
  53. imgproxykit-0.5.0/imgproxykit/options/watermark.py +236 -0
  54. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/width.py +2 -3
  55. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/zoom.py +3 -3
  56. imgproxykit-0.5.0/imgproxykit/serialization.py +149 -0
  57. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/signing.py +5 -7
  58. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/transform.py +28 -16
  59. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/types.py +24 -69
  60. imgproxykit-0.5.0/imgproxykit/variants.py +91 -0
  61. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/pyproject.toml +18 -9
  62. imgproxykit-0.4.0/imgproxykit/internal/encoding.py +0 -12
  63. imgproxykit-0.4.0/imgproxykit/options/background.py +0 -45
  64. imgproxykit-0.4.0/imgproxykit/options/expires.py +0 -27
  65. imgproxykit-0.4.0/imgproxykit/options/gravity.py +0 -52
  66. imgproxykit-0.4.0/imgproxykit/options/resize.py +0 -54
  67. imgproxykit-0.4.0/imgproxykit/options/watermark.py +0 -59
  68. imgproxykit-0.4.0/imgproxykit/serialization.py +0 -118
  69. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/LICENSE +0 -0
  70. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/__init__.py +0 -0
  71. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/__init__.py +0 -0
  72. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/__init__.py +0 -0
  73. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/apps.py +0 -0
  74. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/client.py +0 -0
  75. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/templatetags/__init__.py +0 -0
  76. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/django/templatetags/imgproxykit.py +0 -0
  77. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/fastapi/__init__.py +0 -0
  78. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/integrations/fastapi/dependencies.py +0 -0
  79. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/internal/__init__.py +0 -0
  80. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/options/__init__.py +0 -0
  81. {imgproxykit-0.4.0 → imgproxykit-0.5.0}/imgproxykit/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: imgproxykit
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: A typed Python toolkit for building imgproxy URLs
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -21,11 +21,15 @@ Classifier: Programming Language :: Python :: 3 :: Only
21
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
22
  Classifier: Typing :: Typed
23
23
  Provides-Extra: django
24
+ Provides-Extra: drf
24
25
  Provides-Extra: fastapi
25
26
  Requires-Dist: django (>=5.2,<7) ; extra == "django"
27
+ Requires-Dist: django (>=5.2,<7) ; extra == "drf"
28
+ Requires-Dist: djangorestframework (>=3.16,<4) ; extra == "drf"
26
29
  Requires-Dist: fastapi (>=0.135.2,<1) ; extra == "fastapi"
27
30
  Requires-Dist: typing-extensions (>=4.16,<5)
28
31
  Project-URL: Changelog, https://github.com/kondratevdev/imgproxykit/releases
32
+ Project-URL: Documentation, https://imgproxykit.readthedocs.io/en/latest/
29
33
  Project-URL: GitHub, https://github.com/kondratevdev/imgproxykit
30
34
  Project-URL: Issues, https://github.com/kondratevdev/imgproxykit/issues
31
35
  Description-Content-Type: text/markdown
@@ -49,27 +53,37 @@ Description-Content-Type: text/markdown
49
53
  ## Features
50
54
 
51
55
  - [x] Fully typed and checked with `mypy`, `pyright`, `ty` and `pyrefly` in strict modes
56
+ - [x] Signed URLs using your `imgproxy` server's `key` and `salt`
52
57
  - [x] Immutable, reusable transforms combining typed options and scalar arguments
53
58
  - [x] Variants: generate multiple image URLs from a reusable set of transforms
54
- - [x] Support for named presets configured on your imgproxy server
55
- - [x] Native `Django` integration with settings, shortcuts, and template tags
56
- - [x] Native `FastAPI` integration with dependency injection
59
+ - [x] Support for named presets configured on your `imgproxy` server
60
+ - [x] `Django`, `Django Modern REST`, `Django REST Framework`, `FastAPI` integration
57
61
 
58
62
  ---------
59
63
 
60
64
  ## Installation
61
65
 
62
- Requires **Python 3.12+** and a running [imgproxy](https://github.com/imgproxy/imgproxy) server.
66
+ Requires **Python 3.12+**. A running [imgproxy](https://github.com/imgproxy/imgproxy)
67
+ server is needed to serve images from the generated URLs.
63
68
 
64
69
  ```bash
65
70
  pip install imgproxykit
66
71
  ```
67
72
 
73
+ There are several included extras:
74
+
75
+ - `'imgproxykit[django]'` provides [Django integration](https://imgproxykit.readthedocs.io/en/latest/pages/integrations/django.html)
76
+ with settings, shortcuts, and template tags
77
+ - `'imgproxykit[drf]'` provides [Django REST Framework integration](https://imgproxykit.readthedocs.io/en/latest/pages/integrations/drf.html)
78
+ with serializer fields for image URLs and named variants
79
+ - `'imgproxykit[fastapi]'` provides [FastAPI integration](https://imgproxykit.readthedocs.io/en/latest/pages/integrations/fastapi.html)
80
+ with client registration and dependency injection
81
+
68
82
  ## Examples
69
83
 
70
84
  ### Single URL
71
85
 
72
- Build a URL for a cropped WebP thumbnail:
86
+ Build a URL for a cropped `webp` thumbnail:
73
87
 
74
88
  ```python
75
89
  >>> from imgproxykit import Client, Transform
@@ -79,7 +93,7 @@ Build a URL for a cropped WebP thumbnail:
79
93
  >>> client = Client('https://imgproxy.example.com')
80
94
 
81
95
  >>> thumbnail = Transform(
82
- ... Resize(width=300, height=300, mode='fill'), # Pass typed option objects.
96
+ ... Resize.fill(width=300, height=300), # Pass typed option objects.
83
97
  ... quality=80, # Or scalar keywords, equivalent to Quality(80).
84
98
  ... format='webp',
85
99
  ... )
@@ -89,12 +103,17 @@ Build a URL for a cropped WebP thumbnail:
89
103
 
90
104
  ```
91
105
 
92
- `thumbnail_url` points to a 300×300 WebP thumbnail with smart cropping.
93
- Imgproxy fetches and processes the original image when this URL is requested.
106
+ The generated URL has this structure, with the source URL encoded as URL-safe Base64:
107
+
108
+ ```text
109
+ https://imgproxy.example.com/unsafe/resize:fill:300:300/quality:80/format:webp/<encoded-source>
110
+ ```
111
+
112
+ `thumbnail_url` points to a cropped `webp` thumbnail.
94
113
 
95
114
  ### Variants
96
115
 
97
- Build variants by combining shared settings with different sizes:
116
+ Build variants by extending a shared transform with a width for each size:
98
117
 
99
118
  ```python
100
119
  >>> from imgproxykit import Client, Transform
@@ -104,9 +123,9 @@ Build variants by combining shared settings with different sizes:
104
123
  >>> # Share quality and output format across all variants.
105
124
  >>> base = Transform(quality=85, format='webp')
106
125
  >>> products = {
107
- ... 'small': Transform(*base.options, width=320),
108
- ... 'medium': Transform(*base.options, width=640),
109
- ... 'large': Transform(*base.options, width=1280),
126
+ ... 'small': base.extend(width=320),
127
+ ... 'medium': base.extend(width=640),
128
+ ... 'large': base.extend(width=1280),
110
129
  ... }
111
130
 
112
131
  >>> source_url = 'https://originals.example.com/products/backpack.jpg'
@@ -117,13 +136,14 @@ Build variants by combining shared settings with different sizes:
117
136
  ```
118
137
 
119
138
  `product_urls` contains a URL for each size, all using the shared quality
120
- and WebP format. Reuse `products` with other source images to keep the same
121
- variants across your catalog.
139
+ and WebP format.
122
140
 
123
141
  ## Next steps
124
142
 
125
143
  - Read the [documentation](https://imgproxykit.readthedocs.io/en/latest/)
126
144
  for client configuration, transformations, variants, and processing options.
145
+ - Check the [changelog](https://imgproxykit.readthedocs.io/en/latest/pages/changelog.html)
146
+ for new features, fixes, and breaking changes.
127
147
  - Find published releases on [PyPI](https://pypi.org/project/imgproxykit/).
128
148
 
129
149
  ## Contributing
@@ -17,27 +17,37 @@
17
17
  ## Features
18
18
 
19
19
  - [x] Fully typed and checked with `mypy`, `pyright`, `ty` and `pyrefly` in strict modes
20
+ - [x] Signed URLs using your `imgproxy` server's `key` and `salt`
20
21
  - [x] Immutable, reusable transforms combining typed options and scalar arguments
21
22
  - [x] Variants: generate multiple image URLs from a reusable set of transforms
22
- - [x] Support for named presets configured on your imgproxy server
23
- - [x] Native `Django` integration with settings, shortcuts, and template tags
24
- - [x] Native `FastAPI` integration with dependency injection
23
+ - [x] Support for named presets configured on your `imgproxy` server
24
+ - [x] `Django`, `Django Modern REST`, `Django REST Framework`, `FastAPI` integration
25
25
 
26
26
  ---------
27
27
 
28
28
  ## Installation
29
29
 
30
- Requires **Python 3.12+** and a running [imgproxy](https://github.com/imgproxy/imgproxy) server.
30
+ Requires **Python 3.12+**. A running [imgproxy](https://github.com/imgproxy/imgproxy)
31
+ server is needed to serve images from the generated URLs.
31
32
 
32
33
  ```bash
33
34
  pip install imgproxykit
34
35
  ```
35
36
 
37
+ There are several included extras:
38
+
39
+ - `'imgproxykit[django]'` provides [Django integration](https://imgproxykit.readthedocs.io/en/latest/pages/integrations/django.html)
40
+ with settings, shortcuts, and template tags
41
+ - `'imgproxykit[drf]'` provides [Django REST Framework integration](https://imgproxykit.readthedocs.io/en/latest/pages/integrations/drf.html)
42
+ with serializer fields for image URLs and named variants
43
+ - `'imgproxykit[fastapi]'` provides [FastAPI integration](https://imgproxykit.readthedocs.io/en/latest/pages/integrations/fastapi.html)
44
+ with client registration and dependency injection
45
+
36
46
  ## Examples
37
47
 
38
48
  ### Single URL
39
49
 
40
- Build a URL for a cropped WebP thumbnail:
50
+ Build a URL for a cropped `webp` thumbnail:
41
51
 
42
52
  ```python
43
53
  >>> from imgproxykit import Client, Transform
@@ -47,7 +57,7 @@ Build a URL for a cropped WebP thumbnail:
47
57
  >>> client = Client('https://imgproxy.example.com')
48
58
 
49
59
  >>> thumbnail = Transform(
50
- ... Resize(width=300, height=300, mode='fill'), # Pass typed option objects.
60
+ ... Resize.fill(width=300, height=300), # Pass typed option objects.
51
61
  ... quality=80, # Or scalar keywords, equivalent to Quality(80).
52
62
  ... format='webp',
53
63
  ... )
@@ -57,12 +67,17 @@ Build a URL for a cropped WebP thumbnail:
57
67
 
58
68
  ```
59
69
 
60
- `thumbnail_url` points to a 300×300 WebP thumbnail with smart cropping.
61
- Imgproxy fetches and processes the original image when this URL is requested.
70
+ The generated URL has this structure, with the source URL encoded as URL-safe Base64:
71
+
72
+ ```text
73
+ https://imgproxy.example.com/unsafe/resize:fill:300:300/quality:80/format:webp/<encoded-source>
74
+ ```
75
+
76
+ `thumbnail_url` points to a cropped `webp` thumbnail.
62
77
 
63
78
  ### Variants
64
79
 
65
- Build variants by combining shared settings with different sizes:
80
+ Build variants by extending a shared transform with a width for each size:
66
81
 
67
82
  ```python
68
83
  >>> from imgproxykit import Client, Transform
@@ -72,9 +87,9 @@ Build variants by combining shared settings with different sizes:
72
87
  >>> # Share quality and output format across all variants.
73
88
  >>> base = Transform(quality=85, format='webp')
74
89
  >>> products = {
75
- ... 'small': Transform(*base.options, width=320),
76
- ... 'medium': Transform(*base.options, width=640),
77
- ... 'large': Transform(*base.options, width=1280),
90
+ ... 'small': base.extend(width=320),
91
+ ... 'medium': base.extend(width=640),
92
+ ... 'large': base.extend(width=1280),
78
93
  ... }
79
94
 
80
95
  >>> source_url = 'https://originals.example.com/products/backpack.jpg'
@@ -85,13 +100,14 @@ Build variants by combining shared settings with different sizes:
85
100
  ```
86
101
 
87
102
  `product_urls` contains a URL for each size, all using the shared quality
88
- and WebP format. Reuse `products` with other source images to keep the same
89
- variants across your catalog.
103
+ and WebP format.
90
104
 
91
105
  ## Next steps
92
106
 
93
107
  - Read the [documentation](https://imgproxykit.readthedocs.io/en/latest/)
94
108
  for client configuration, transformations, variants, and processing options.
109
+ - Check the [changelog](https://imgproxykit.readthedocs.io/en/latest/pages/changelog.html)
110
+ for new features, fixes, and breaking changes.
95
111
  - Find published releases on [PyPI](https://pypi.org/project/imgproxykit/).
96
112
 
97
113
  ## Contributing
@@ -1,9 +1,18 @@
1
1
  from collections.abc import Mapping
2
- from typing import ClassVar, overload
2
+ from typing import TYPE_CHECKING, ClassVar, overload
3
3
 
4
4
  from imgproxykit.serialization import PathSerializer
5
5
  from imgproxykit.signing import UrlSigner
6
6
  from imgproxykit.transform import Transform
7
+ from imgproxykit.types import SourceEncoding
8
+ from imgproxykit.variants import DataclassVariantsResolver
9
+
10
+ if TYPE_CHECKING:
11
+ from _typeshed import DataclassInstance
12
+
13
+ type _VariantsResult[Key: str] = (
14
+ dict[Key, str] | dict[str, str] | DataclassInstance
15
+ )
7
16
 
8
17
 
9
18
  class Client:
@@ -11,17 +20,12 @@ class Client:
11
20
  Build imgproxy URLs from Python transforms or server presets.
12
21
 
13
22
  Stores the imgproxy address and signing configuration for reuse across
14
- images. Each call to :meth:`url` returns a URL string; imgproxy loads
15
- the source and processes the image when that URL is requested.
23
+ images. Imgproxy loads the source and processes the image when
24
+ that URL is requested.
16
25
 
17
26
  Pass processing options through :class:`~imgproxykit.Transform` as
18
27
  option instances or scalar keyword arguments. Preset options reference
19
28
  names configured on the imgproxy server.
20
-
21
- Subclass this client and override :attr:`path_serializer_cls` or
22
- :attr:`url_signer_cls` to customize path construction or signing.
23
- Each client creates its own instances of these components.
24
-
25
29
  """
26
30
 
27
31
  __slots__ = (
@@ -34,6 +38,10 @@ class Client:
34
38
  path_serializer_cls: ClassVar[type[PathSerializer]] = PathSerializer
35
39
  #: Component that signs paths or returns the unsigned URL marker.
36
40
  url_signer_cls: ClassVar[type[UrlSigner]] = UrlSigner
41
+ #: Component that validates dataclass variant declarations.
42
+ variants_resolver_cls: ClassVar[type[DataclassVariantsResolver]] = (
43
+ DataclassVariantsResolver
44
+ )
37
45
 
38
46
  @overload
39
47
  def __init__(
@@ -43,8 +51,10 @@ class Client:
43
51
  *,
44
52
  key: None = None,
45
53
  salt: None = None,
46
- unsigned_signature: str = 'unsafe',
47
- arguments_separator: str = ':',
54
+ source_encoding: SourceEncoding = 'base64',
55
+ unsigned_marker: str = 'unsafe',
56
+ argument_separator: str = ':',
57
+ use_short_options: bool = False,
48
58
  ) -> None: ...
49
59
 
50
60
  @overload
@@ -55,8 +65,10 @@ class Client:
55
65
  *,
56
66
  key: str,
57
67
  salt: str,
68
+ source_encoding: SourceEncoding = 'base64',
58
69
  signature_size: int = 32,
59
- arguments_separator: str = ':',
70
+ argument_separator: str = ':',
71
+ use_short_options: bool = False,
60
72
  ) -> None: ...
61
73
 
62
74
  def __init__( # noqa: WPS211
@@ -66,9 +78,11 @@ class Client:
66
78
  *,
67
79
  key: str | None = None,
68
80
  salt: str | None = None,
81
+ source_encoding: SourceEncoding = 'base64',
69
82
  signature_size: int = 32,
70
- unsigned_signature: str = 'unsafe',
71
- arguments_separator: str = ':',
83
+ unsigned_marker: str = 'unsafe',
84
+ argument_separator: str = ':',
85
+ use_short_options: bool = False,
72
86
  ) -> None:
73
87
  """
74
88
  Configure the imgproxy address and create the client components.
@@ -83,29 +97,37 @@ class Client:
83
97
  stored as supplied, without validation.
84
98
  key: Nonempty hex-encoded signing key matching the server.
85
99
  Supply together with ``salt``; ``None`` selects unsigned mode.
100
+ See `IMGPROXY_KEY
101
+ <https://docs.imgproxy.net/configuration/options#url-signature>`__.
86
102
  salt: Nonempty hex-encoded signing salt matching the server.
87
103
  Supply together with ``key``; ``None`` selects unsigned mode.
104
+ See `IMGPROXY_SALT
105
+ <https://docs.imgproxy.net/configuration/options#url-signature>`__.
88
106
  signature_size: Positive digest byte count to encode. Must match
89
107
  the server's `IMGPROXY_SIGNATURE_SIZE
90
108
  <https://docs.imgproxy.net/latest/configuration/options#url-signature>`__.
91
- Defaults to ``32``.
92
- Values of 32 or more use the full digest.
93
- unsigned_signature: URL marker used when key and salt are omitted.
109
+ unsigned_marker: URL marker used when key and salt are omitted.
94
110
  Defaults to ``'unsafe'``. With server signing enabled,
95
111
  configure this marker in `IMGPROXY_TRUSTED_SIGNATURES
96
112
  <https://docs.imgproxy.net/latest/configuration/options#url-signature>`__.
97
- arguments_separator: Separator between processing option names
113
+ argument_separator: Separator between processing option names
98
114
  and their arguments. Must match the server's
99
115
  `IMGPROXY_ARGUMENTS_SEPARATOR
100
116
  <https://docs.imgproxy.net/latest/configuration/options#miscellaneous>`__.
101
- Defaults to ``':'``.
117
+ source_encoding: Source URL representation: ``'base64'`` or
118
+ ``'plain'`` with full percent-encoding. See
119
+ `imgproxy source URLs
120
+ <https://docs.imgproxy.net/usage/processing#source-url>`__.
121
+ use_short_options: Use short processing option aliases when
122
+ available, falling back to full names. Defaults to ``False``.
102
123
 
103
124
  Raises:
104
125
  ValueError: With the default signer, if only one signing
105
126
  credential is supplied, either is empty or invalid hex,
106
127
  or ``signature_size`` is not positive, even in unsigned mode.
107
128
 
108
- Examples:
129
+ Usage:
130
+
109
131
  Create an unsigned client:
110
132
 
111
133
  >>> from imgproxykit import Client
@@ -118,18 +140,19 @@ class Client:
118
140
  ... key='736563726574',
119
141
  ... salt='73616c74',
120
142
  ... )
121
-
122
143
  """
123
144
  # Prepare `base_url` only once pre instance
124
145
  self._base_url = base_url.rstrip('/')
125
146
  self._path_serializer = self.path_serializer_cls(
126
- arguments_separator=arguments_separator,
147
+ argument_separator=argument_separator,
148
+ use_short_options=use_short_options,
149
+ source_encoding=source_encoding,
127
150
  )
128
151
  self._url_signer = self.url_signer_cls(
129
152
  key=key,
130
153
  salt=salt,
131
154
  signature_size=signature_size,
132
- unsigned_signature=unsigned_signature,
155
+ unsigned_marker=unsigned_marker,
133
156
  )
134
157
 
135
158
  def url(
@@ -151,9 +174,9 @@ class Client:
151
174
 
152
175
  Args:
153
176
  source: Complete source URI understood by the imgproxy server.
154
- The default serializer encodes its UTF-8 representation as
155
- URL-safe Base64 without padding. The URI is neither validated
156
- nor resolved against ``base_url``.
177
+ The default serializer uses URL-safe Base64 without padding
178
+ or percent-encoding according to ``source_encoding``. The URI
179
+ is neither validated nor resolved against ``base_url``.
157
180
  transform: Reusable processing options and optional output format.
158
181
  Omit or pass ``None`` to add no processing options.
159
182
 
@@ -166,28 +189,53 @@ class Client:
166
189
  signature = self._url_signer(path)
167
190
  return f'{self._base_url}/{signature}{path}'
168
191
 
192
+ @overload
169
193
  def variants[Key: str](
170
194
  self,
171
195
  source: str,
172
196
  *,
173
197
  variants: Mapping[Key, Transform],
174
- ) -> dict[Key, str]:
198
+ ) -> dict[Key, str]: ...
199
+
200
+ @overload
201
+ def variants[VariantSet: DataclassInstance](
202
+ self,
203
+ source: str,
204
+ *,
205
+ variants: type[VariantSet],
206
+ ) -> VariantSet: ...
207
+
208
+ def variants[Key: str](
209
+ self,
210
+ source: str,
211
+ *,
212
+ variants: Mapping[Key, Transform] | type['DataclassInstance'],
213
+ ) -> _VariantsResult[Key]:
175
214
  """
176
215
  Build named URLs for one source using complete transformations.
177
216
 
178
217
  Args:
179
218
  source: Complete source URI understood by the imgproxy server.
180
219
  variants: Names mapped to the transformation for each variant.
181
- Each transformation is passed unchanged to :meth:`url`.
220
+ Alternatively, a dataclass class with fields declared as
221
+ ``Annotated[str, Transform(...)]``. Each transformation is
222
+ passed unchanged to :meth:`url`.
182
223
 
183
224
  Returns:
184
225
  A new dictionary preserving the input keys and iteration order.
185
226
  The key type is preserved, including literal string unions.
186
227
  An empty mapping produces an empty dictionary.
228
+ A dataclass class produces a new instance of that exact class,
229
+ with a generated URL in every field.
187
230
  No network request is made.
188
-
189
231
  """
190
- return {
191
- name: self.url(source, transform=transform)
192
- for name, transform in variants.items()
232
+ transforms = (
233
+ variants
234
+ if isinstance(variants, Mapping)
235
+ else self.variants_resolver_cls(model=variants)()
236
+ )
237
+ urls = {
238
+ name: self.url(source, transform=transform) # ty: ignore[invalid-argument-type]
239
+ for name, transform in transforms.items()
193
240
  }
241
+ return urls if isinstance(variants, Mapping) else variants(**urls) # ty: ignore[invalid-return-type, invalid-argument-type]
@@ -7,6 +7,7 @@ from django.db.models.fields.files import FieldFile
7
7
  from typing_extensions import TypedDict
8
8
 
9
9
  from imgproxykit.transform import Transform
10
+ from imgproxykit.types import SourceEncoding
10
11
 
11
12
  #: Django setting containing the imgproxy client configuration.
12
13
  IMGPROXYKIT_SETTINGS: Final = 'IMGPROXYKIT'
@@ -21,8 +22,10 @@ class ClientSettings(enum.StrEnum):
21
22
  key = 'key'
22
23
  salt = 'salt'
23
24
  signature_size = 'signature_size'
24
- unsigned_signature = 'unsigned_signature'
25
- arguments_separator = 'arguments_separator'
25
+ unsigned_marker = 'unsigned_marker'
26
+ argument_separator = 'argument_separator'
27
+ use_short_options = 'use_short_options'
28
+ source_encoding = 'source_encoding'
26
29
 
27
30
 
28
31
  @final
@@ -48,9 +51,13 @@ class ClientSettingsDict(TypedDict, total=False, closed=True):
48
51
  #: Positive signature digest byte count; must match the server.
49
52
  signature_size: int
50
53
  #: Signature marker used when signing credentials are omitted.
51
- unsigned_signature: str
54
+ unsigned_marker: str
52
55
  #: Processing argument separator; must match the server.
53
- arguments_separator: str
56
+ argument_separator: str
57
+ #: Use short processing option aliases when available.
58
+ use_short_options: bool
59
+ #: Source URL representation using Base64 or percent-encoded plain mode.
60
+ source_encoding: SourceEncoding
54
61
 
55
62
 
56
63
  class SettingsDict(TypedDict, total=False, closed=True):
@@ -97,7 +104,6 @@ def get_config() -> SettingsDict:
97
104
 
98
105
  Raises:
99
106
  ImproperlyConfigured: If ``IMGPROXYKIT`` is missing or ``None``.
100
-
101
107
  """
102
108
  # Keep LazySettings out of module globals: doctest inspection evaluates it.
103
109
  from django.conf import settings # noqa: PLC0415
@@ -27,7 +27,6 @@ def imgproxy_url(
27
27
  Raises:
28
28
  KeyError: If a named transformation is not configured.
29
29
  ValueError: If the default source resolver receives an empty file field.
30
-
31
30
  """
32
31
  if isinstance(transform, str):
33
32
  transform = get_config()[Settings.transforms.value][transform] # pyright: ignore[reportTypedDictNotRequiredAccess]
@@ -66,7 +65,6 @@ def imgproxy_variants[Key: str](
66
65
  Raises:
67
66
  KeyError: If a named variant set is not configured.
68
67
  ValueError: If the default source resolver receives an empty file field.
69
-
70
68
  """
71
69
  client = get_client()
72
70
 
@@ -22,7 +22,6 @@ def resolve_source(source: str | FieldFile) -> str:
22
22
 
23
23
  Returns:
24
24
  Source URI to pass to the configured client.
25
-
26
25
  """
27
26
  resolver = get_config()[Settings.source_resolver.value] # pyright: ignore[reportTypedDictNotRequiredAccess]
28
27
  if isinstance(resolver, str):
@@ -39,6 +38,5 @@ def default_source_resolver(source: str | FieldFile) -> str:
39
38
  Raises:
40
39
  ValueError: If the file field has no associated file, as with
41
40
  direct access to ``FieldFile.url``.
42
-
43
41
  """
44
42
  return source.url if isinstance(source, FieldFile) else source
@@ -0,0 +1,16 @@
1
+ # Optional integrations check their dependencies before importing adapters.
2
+ # flake8: noqa: WPS412
3
+ try: # noqa: RUF067
4
+ import rest_framework # noqa: F401 # pyright: ignore[reportUnusedImport]
5
+ except ImportError as exc: # pragma: no cover
6
+ raise ImportError(
7
+ 'The DRF integration requires Django REST Framework. '
8
+ "Install it with `pip install 'imgproxykit[drf]'`.",
9
+ ) from exc
10
+
11
+ from imgproxykit.integrations.drf.serializers import (
12
+ ImgproxyURLField as ImgproxyURLField,
13
+ )
14
+ from imgproxykit.integrations.drf.serializers import (
15
+ ImgproxyVariantsField as ImgproxyVariantsField,
16
+ )
@@ -0,0 +1,117 @@
1
+ from collections.abc import Mapping
2
+ from typing import Any, override
3
+
4
+ from django.db.models.fields.files import FieldFile
5
+ from rest_framework import serializers
6
+
7
+ from imgproxykit.integrations.django import imgproxy_url, imgproxy_variants
8
+ from imgproxykit.transform import Transform
9
+
10
+
11
+ class ImgproxyURLField(serializers.URLField):
12
+ """
13
+ Represent a source string or model file as a read-only imgproxy URL.
14
+
15
+ Use Django's ``IMGPROXYKIT`` settings without request context. Empty
16
+ sources return ``None`` without calling the source resolver.
17
+ ``read_only`` must be ``True`` and ``write_only`` must be ``False``.
18
+
19
+ Args:
20
+ transform: Transformation or name from ``IMGPROXYKIT['transforms']``.
21
+ Omit to add no processing options.
22
+ **kwargs: DRF field options. ``allow_null`` defaults to ``True``.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ transform: Transform | str | None = None,
29
+ **kwargs: Any,
30
+ ) -> None:
31
+ """Configure the transformation and DRF field options."""
32
+ # Remove these options before forwarding kwargs: their values are fixed
33
+ # below, and passing them twice would raise TypeError.
34
+ if kwargs.pop('read_only', True) is not True:
35
+ raise ValueError('read_only must be True for ImgproxyURLField.')
36
+
37
+ if kwargs.pop('write_only', False) is not False:
38
+ raise ValueError('write_only must be False for ImgproxyURLField.')
39
+
40
+ kwargs.setdefault('allow_null', True)
41
+ super().__init__( # pyright: ignore[reportUnknownMemberType]
42
+ read_only=True,
43
+ write_only=False,
44
+ **kwargs,
45
+ )
46
+ self.transform = transform
47
+
48
+ # Empty sources produce None, which URLField's return type excludes.
49
+ @override
50
+ def to_representation( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override]
51
+ self,
52
+ value: str | FieldFile | None,
53
+ ) -> str | None:
54
+ """Build an imgproxy URL, or return None for an empty source."""
55
+ if not value:
56
+ return None
57
+
58
+ return imgproxy_url(value, self.transform)
59
+
60
+
61
+ class ImgproxyVariantsField(serializers.DictField):
62
+ """
63
+ Represent a source as a read-only dictionary of named imgproxy URLs.
64
+
65
+ Use Django's ``IMGPROXYKIT`` settings and resolve the source once for
66
+ all variants. Empty sources return ``None`` without calling the resolver.
67
+ ``read_only`` must be ``True`` and ``write_only`` must be ``False``.
68
+ ``child`` cannot be supplied; variant values always use a URL field.
69
+
70
+ Args:
71
+ variants: Transformation mapping or set name from
72
+ ``IMGPROXYKIT['variants']``.
73
+ **kwargs: DRF field options. ``allow_null`` defaults to ``True``.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ *,
79
+ variants: Mapping[str, Transform] | str,
80
+ **kwargs: Any,
81
+ ) -> None:
82
+ """Configure the variants and DRF field options."""
83
+ # Remove these options before forwarding kwargs: their values are fixed
84
+ # below, and passing them twice would raise TypeError.
85
+ if kwargs.pop('read_only', True) is not True:
86
+ raise ValueError(
87
+ 'read_only must be True for ImgproxyVariantsField.',
88
+ )
89
+ if kwargs.pop('write_only', False) is not False:
90
+ raise ValueError(
91
+ 'write_only must be False for ImgproxyVariantsField.',
92
+ )
93
+ if 'child' in kwargs:
94
+ raise TypeError(
95
+ 'child cannot be supplied for ImgproxyVariantsField.',
96
+ )
97
+
98
+ kwargs.setdefault('allow_null', True)
99
+ super().__init__( # pyright: ignore[reportUnknownMemberType]
100
+ child=serializers.URLField(),
101
+ read_only=True,
102
+ write_only=False,
103
+ **kwargs,
104
+ )
105
+ self.variants = variants
106
+
107
+ # DictField's types exclude source strings, model files, and None output.
108
+ @override
109
+ def to_representation( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override]
110
+ self,
111
+ value: str | FieldFile | None, # type: ignore[override]
112
+ ) -> dict[str, str] | None:
113
+ """Build named imgproxy URLs, or return None for an empty source."""
114
+ if not value:
115
+ return None
116
+
117
+ return imgproxy_variants(value, self.variants)