imgproxykit 0.2.1__tar.gz → 0.4.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 (73) hide show
  1. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/PKG-INFO +61 -41
  2. imgproxykit-0.4.0/README.md +111 -0
  3. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/client.py +49 -9
  4. imgproxykit-0.4.0/imgproxykit/integrations/django/__init__.py +29 -0
  5. imgproxykit-0.4.0/imgproxykit/integrations/django/apps.py +8 -0
  6. imgproxykit-0.4.0/imgproxykit/integrations/django/client.py +39 -0
  7. imgproxykit-0.4.0/imgproxykit/integrations/django/settings.py +115 -0
  8. imgproxykit-0.4.0/imgproxykit/integrations/django/shortcuts.py +79 -0
  9. imgproxykit-0.4.0/imgproxykit/integrations/django/sources.py +44 -0
  10. imgproxykit-0.4.0/imgproxykit/integrations/django/templatetags/imgproxykit.py +12 -0
  11. imgproxykit-0.4.0/imgproxykit/integrations/fastapi/__init__.py +13 -0
  12. imgproxykit-0.4.0/imgproxykit/integrations/fastapi/dependencies.py +53 -0
  13. imgproxykit-0.4.0/imgproxykit/internal/__init__.py +0 -0
  14. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/expires.py +4 -6
  15. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/max_animation_frame_resolution.py +3 -1
  16. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/max_animation_frames.py +3 -1
  17. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/max_result_dimension.py +3 -1
  18. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/max_src_file_size.py +3 -1
  19. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/max_src_resolution.py +3 -1
  20. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/preset.py +23 -2
  21. imgproxykit-0.4.0/imgproxykit/py.typed +0 -0
  22. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/serialization.py +21 -9
  23. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/signing.py +17 -13
  24. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/transform.py +1 -8
  25. imgproxykit-0.4.0/imgproxykit/types.py +161 -0
  26. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/pyproject.toml +40 -14
  27. imgproxykit-0.2.1/README.md +0 -95
  28. imgproxykit-0.2.1/imgproxykit/types.py +0 -95
  29. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/LICENSE +0 -0
  30. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/__init__.py +0 -0
  31. {imgproxykit-0.2.1/imgproxykit/internal → imgproxykit-0.4.0/imgproxykit/integrations}/__init__.py +0 -0
  32. /imgproxykit-0.2.1/imgproxykit/py.typed → /imgproxykit-0.4.0/imgproxykit/integrations/django/templatetags/__init__.py +0 -0
  33. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/internal/encoding.py +0 -0
  34. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/__init__.py +0 -0
  35. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/auto_rotate.py +0 -0
  36. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/background.py +0 -0
  37. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/base.py +0 -0
  38. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/blur.py +0 -0
  39. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/cache_buster.py +0 -0
  40. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/crop.py +0 -0
  41. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/dpr.py +0 -0
  42. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/enforce_thumbnail.py +0 -0
  43. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/enlarge.py +0 -0
  44. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/extend.py +0 -0
  45. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/extend_aspect_ratio.py +0 -0
  46. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/filename.py +0 -0
  47. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/flip.py +0 -0
  48. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/format.py +0 -0
  49. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/format_quality.py +0 -0
  50. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/gravity.py +0 -0
  51. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/height.py +0 -0
  52. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/keep_copyright.py +0 -0
  53. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/max_bytes.py +0 -0
  54. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/min_height.py +0 -0
  55. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/min_width.py +0 -0
  56. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/padding.py +0 -0
  57. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/pixelate.py +0 -0
  58. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/preserve_hdr.py +0 -0
  59. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/quality.py +0 -0
  60. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/raw.py +0 -0
  61. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/resize.py +0 -0
  62. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/resizing_type.py +0 -0
  63. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/return_attachment.py +0 -0
  64. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/rotate.py +0 -0
  65. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/sharpen.py +0 -0
  66. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/size.py +0 -0
  67. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/skip_processing.py +0 -0
  68. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/strip_color_profile.py +0 -0
  69. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/strip_metadata.py +0 -0
  70. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/trim.py +0 -0
  71. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/watermark.py +0 -0
  72. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/width.py +0 -0
  73. {imgproxykit-0.2.1 → imgproxykit-0.4.0}/imgproxykit/options/zoom.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: imgproxykit
3
- Version: 0.2.1
3
+ Version: 0.4.0
4
4
  Summary: A typed Python toolkit for building imgproxy URLs
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -20,6 +20,10 @@ Classifier: Programming Language :: Python :: 3.15
20
20
  Classifier: Programming Language :: Python :: 3 :: Only
21
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
22
  Classifier: Typing :: Typed
23
+ Provides-Extra: django
24
+ Provides-Extra: fastapi
25
+ Requires-Dist: django (>=5.2,<7) ; extra == "django"
26
+ Requires-Dist: fastapi (>=0.135.2,<1) ; extra == "fastapi"
23
27
  Requires-Dist: typing-extensions (>=4.16,<5)
24
28
  Project-URL: Changelog, https://github.com/kondratevdev/imgproxykit/releases
25
29
  Project-URL: GitHub, https://github.com/kondratevdev/imgproxykit
@@ -45,67 +49,83 @@ Description-Content-Type: text/markdown
45
49
  ## Features
46
50
 
47
51
  - [x] Fully typed and checked with `mypy`, `pyright`, `ty` and `pyrefly` in strict modes
48
- - [x] Expressive transforms: combine option objects with concise scalar arguments
49
- - [x] Immutable, reusable transforms for consistent image settings across your app
52
+ - [x] Immutable, reusable transforms combining typed options and scalar arguments
53
+ - [x] Variants: generate multiple image URLs from a reusable set of transforms
50
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
51
57
 
52
58
  ---------
53
59
 
54
60
  ## Installation
55
61
 
56
- Requires **Python 3.12+** and a running imgproxy server.
62
+ Requires **Python 3.12+** and a running [imgproxy](https://github.com/imgproxy/imgproxy) server.
57
63
 
58
64
  ```bash
59
65
  pip install imgproxykit
60
66
  ```
61
67
 
62
- ## Example
68
+ ## Examples
63
69
 
64
- Define a WebP thumbnail once and reuse it across a product catalog:
70
+ ### Single URL
71
+
72
+ Build a URL for a cropped WebP thumbnail:
65
73
 
66
74
  ```python
67
- from imgproxykit import Client, Transform
68
- from imgproxykit.options import Gravity, Resize
69
-
70
- client = Client('https://imgproxy.your-app.com') # Your imgproxy server.
71
-
72
- thumbnail = Transform(
73
- Resize(width=300, height=300, mode='fill'), # Pass option objects.
74
- Gravity(position='sm'), # Let imgproxy choose the crop's focus.
75
- quality=80, # Or scalar, equivalent to Quality(80).
76
- format='webp',
77
- )
78
- sources = [
79
- 'https://example.com/products/backpack.jpg',
80
- 'https://example.com/products/sneakers.jpg',
81
- ]
82
- thumbnail_urls = [client.url(source, transform=thumbnail) for source in sources]
75
+ >>> from imgproxykit import Client, Transform
76
+ >>> from imgproxykit.options import Resize
77
+
78
+ >>> # Public URL of your imgproxy server.
79
+ >>> client = Client('https://imgproxy.example.com')
80
+
81
+ >>> thumbnail = Transform(
82
+ ... Resize(width=300, height=300, mode='fill'), # Pass typed option objects.
83
+ ... quality=80, # Or scalar keywords, equivalent to Quality(80).
84
+ ... format='webp',
85
+ ... )
86
+
87
+ >>> source_url = 'https://originals.example.com/products/backpack.jpg'
88
+ >>> thumbnail_url = client.url(source=source_url, transform=thumbnail)
89
+
83
90
  ```
84
91
 
85
- Use these URLs in your images' `src` attributes; imgproxy handles processing.
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.
94
+
95
+ ### Variants
86
96
 
87
- Sign URLs and reuse presets configured on your imgproxy server:
97
+ Build variants by combining shared settings with different sizes:
88
98
 
89
99
  ```python
90
- from imgproxykit import Client, Transform
91
- from imgproxykit.options import Preset
92
-
93
- client = Client(
94
- 'https://imgproxy.your-app.com',
95
- key='736563726574', # Example hex credentials; use your server's values.
96
- salt='73616c74',
97
- )
98
-
99
- thumbnail = Transform(
100
- Preset(names=('product-card',)),
101
- format='webp',
102
- )
103
- thumbnail_url = client.url(
104
- 'https://example.com/products/backpack.jpg',
105
- transform=product_card,
106
- )
100
+ >>> from imgproxykit import Client, Transform
101
+
102
+ >>> client = Client('https://imgproxy.example.com')
103
+
104
+ >>> # Share quality and output format across all variants.
105
+ >>> base = Transform(quality=85, format='webp')
106
+ >>> products = {
107
+ ... 'small': Transform(*base.options, width=320),
108
+ ... 'medium': Transform(*base.options, width=640),
109
+ ... 'large': Transform(*base.options, width=1280),
110
+ ... }
111
+
112
+ >>> source_url = 'https://originals.example.com/products/backpack.jpg'
113
+ >>> # Build one URL per variant for the same source image.
114
+ >>> product_urls = client.variants(source=source_url, variants=products)
115
+ >>> small_url = product_urls['small'] # Access a URL by its variant name.
116
+
107
117
  ```
108
118
 
119
+ `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.
122
+
123
+ ## Next steps
124
+
125
+ - Read the [documentation](https://imgproxykit.readthedocs.io/en/latest/)
126
+ for client configuration, transformations, variants, and processing options.
127
+ - Find published releases on [PyPI](https://pypi.org/project/imgproxykit/).
128
+
109
129
  ## Contributing
110
130
 
111
131
  See the [contributing guide](CONTRIBUTING.md) for development setup and checks.
@@ -0,0 +1,111 @@
1
+ <h1 align="center">imgproxykit</h1>
2
+
3
+ <p align="center">
4
+ <em>A typed Python toolkit for building imgproxy URLs.</em>
5
+ </p>
6
+
7
+ <div align="center">
8
+
9
+ [![Tests Result](https://img.shields.io/github/actions/workflow/status/kondratevdev/imgproxykit/test.yml?branch=master&label=tests&labelColor=black&color=blue)](https://github.com/kondratevdev/imgproxykit/actions/workflows/test.yml)
10
+ [![PyPI Version](https://img.shields.io/pypi/v/imgproxykit.svg?labelColor=black&color=blue)](https://pypi.org/project/imgproxykit/)
11
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/imgproxykit?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=BLUE&left_text=downloads)](https://pepy.tech/projects/imgproxykit)
12
+ [![Supported Python Version](https://img.shields.io/pypi/pyversions/imgproxykit.svg?labelColor=black&color=blue)](https://pypi.org/project/imgproxykit/)
13
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg?labelColor=black)](LICENSE)
14
+
15
+ </div>
16
+
17
+ ## Features
18
+
19
+ - [x] Fully typed and checked with `mypy`, `pyright`, `ty` and `pyrefly` in strict modes
20
+ - [x] Immutable, reusable transforms combining typed options and scalar arguments
21
+ - [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
25
+
26
+ ---------
27
+
28
+ ## Installation
29
+
30
+ Requires **Python 3.12+** and a running [imgproxy](https://github.com/imgproxy/imgproxy) server.
31
+
32
+ ```bash
33
+ pip install imgproxykit
34
+ ```
35
+
36
+ ## Examples
37
+
38
+ ### Single URL
39
+
40
+ Build a URL for a cropped WebP thumbnail:
41
+
42
+ ```python
43
+ >>> from imgproxykit import Client, Transform
44
+ >>> from imgproxykit.options import Resize
45
+
46
+ >>> # Public URL of your imgproxy server.
47
+ >>> client = Client('https://imgproxy.example.com')
48
+
49
+ >>> thumbnail = Transform(
50
+ ... Resize(width=300, height=300, mode='fill'), # Pass typed option objects.
51
+ ... quality=80, # Or scalar keywords, equivalent to Quality(80).
52
+ ... format='webp',
53
+ ... )
54
+
55
+ >>> source_url = 'https://originals.example.com/products/backpack.jpg'
56
+ >>> thumbnail_url = client.url(source=source_url, transform=thumbnail)
57
+
58
+ ```
59
+
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.
62
+
63
+ ### Variants
64
+
65
+ Build variants by combining shared settings with different sizes:
66
+
67
+ ```python
68
+ >>> from imgproxykit import Client, Transform
69
+
70
+ >>> client = Client('https://imgproxy.example.com')
71
+
72
+ >>> # Share quality and output format across all variants.
73
+ >>> base = Transform(quality=85, format='webp')
74
+ >>> products = {
75
+ ... 'small': Transform(*base.options, width=320),
76
+ ... 'medium': Transform(*base.options, width=640),
77
+ ... 'large': Transform(*base.options, width=1280),
78
+ ... }
79
+
80
+ >>> source_url = 'https://originals.example.com/products/backpack.jpg'
81
+ >>> # Build one URL per variant for the same source image.
82
+ >>> product_urls = client.variants(source=source_url, variants=products)
83
+ >>> small_url = product_urls['small'] # Access a URL by its variant name.
84
+
85
+ ```
86
+
87
+ `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.
90
+
91
+ ## Next steps
92
+
93
+ - Read the [documentation](https://imgproxykit.readthedocs.io/en/latest/)
94
+ for client configuration, transformations, variants, and processing options.
95
+ - Find published releases on [PyPI](https://pypi.org/project/imgproxykit/).
96
+
97
+ ## Contributing
98
+
99
+ See the [contributing guide](CONTRIBUTING.md) for development setup and checks.
100
+ Bug reports and feature requests are welcome on the
101
+ [issue tracker](https://github.com/kondratevdev/imgproxykit/issues).
102
+
103
+ ## License
104
+
105
+ [MIT](LICENSE)
106
+
107
+ ## Credits
108
+
109
+ Generated with
110
+ [`wemake-python-package`](https://github.com/wemake-services/wemake-python-package)
111
+ ([template version](https://github.com/wemake-services/wemake-python-package/tree/47d9dddd29da8d6d3d1a403f8a143b323a812083)).
@@ -1,3 +1,4 @@
1
+ from collections.abc import Mapping
1
2
  from typing import ClassVar, overload
2
3
 
3
4
  from imgproxykit.serialization import PathSerializer
@@ -43,6 +44,7 @@ class Client:
43
44
  key: None = None,
44
45
  salt: None = None,
45
46
  unsigned_signature: str = 'unsafe',
47
+ arguments_separator: str = ':',
46
48
  ) -> None: ...
47
49
 
48
50
  @overload
@@ -54,9 +56,10 @@ class Client:
54
56
  key: str,
55
57
  salt: str,
56
58
  signature_size: int = 32,
59
+ arguments_separator: str = ':',
57
60
  ) -> None: ...
58
61
 
59
- def __init__(
62
+ def __init__( # noqa: WPS211
60
63
  self,
61
64
  base_url: str,
62
65
  /,
@@ -65,6 +68,7 @@ class Client:
65
68
  salt: str | None = None,
66
69
  signature_size: int = 32,
67
70
  unsigned_signature: str = 'unsafe',
71
+ arguments_separator: str = ':',
68
72
  ) -> None:
69
73
  """
70
74
  Configure the imgproxy address and create the client components.
@@ -82,11 +86,19 @@ class Client:
82
86
  salt: Nonempty hex-encoded signing salt matching the server.
83
87
  Supply together with ``key``; ``None`` selects unsigned mode.
84
88
  signature_size: Positive digest byte count to encode. Must match
85
- the server's ``IMGPROXY_SIGNATURE_SIZE``. Defaults to ``32``.
89
+ the server's `IMGPROXY_SIGNATURE_SIZE
90
+ <https://docs.imgproxy.net/latest/configuration/options#url-signature>`__.
91
+ Defaults to ``32``.
86
92
  Values of 32 or more use the full digest.
87
93
  unsigned_signature: URL marker used when key and salt are omitted.
88
94
  Defaults to ``'unsafe'``. With server signing enabled,
89
- configure this marker in ``IMGPROXY_TRUSTED_SIGNATURES``.
95
+ configure this marker in `IMGPROXY_TRUSTED_SIGNATURES
96
+ <https://docs.imgproxy.net/latest/configuration/options#url-signature>`__.
97
+ arguments_separator: Separator between processing option names
98
+ and their arguments. Must match the server's
99
+ `IMGPROXY_ARGUMENTS_SEPARATOR
100
+ <https://docs.imgproxy.net/latest/configuration/options#miscellaneous>`__.
101
+ Defaults to ``':'``.
90
102
 
91
103
  Raises:
92
104
  ValueError: With the default signer, if only one signing
@@ -97,19 +109,22 @@ class Client:
97
109
  Create an unsigned client:
98
110
 
99
111
  >>> from imgproxykit import Client
100
- >>> client = Client('https://images.example.com')
112
+ >>> client = Client('https://imgproxy.example.com')
101
113
 
102
114
  Create a signed client with example credentials:
103
115
 
104
116
  >>> client = Client(
105
- ... 'https://images.example.com',
117
+ ... 'https://imgproxy.example.com',
106
118
  ... key='736563726574',
107
119
  ... salt='73616c74',
108
120
  ... )
109
121
 
110
122
  """
111
- self._base_url = base_url
112
- self._path_serializer = self.path_serializer_cls()
123
+ # Prepare `base_url` only once pre instance
124
+ self._base_url = base_url.rstrip('/')
125
+ self._path_serializer = self.path_serializer_cls(
126
+ arguments_separator=arguments_separator,
127
+ )
113
128
  self._url_signer = self.url_signer_cls(
114
129
  key=key,
115
130
  salt=salt,
@@ -149,5 +164,30 @@ class Client:
149
164
  """
150
165
  path = self._path_serializer(source, transform=transform)
151
166
  signature = self._url_signer(path)
152
- base_url = self._base_url.rstrip('/')
153
- return f'{base_url}/{signature}{path}'
167
+ return f'{self._base_url}/{signature}{path}'
168
+
169
+ def variants[Key: str](
170
+ self,
171
+ source: str,
172
+ *,
173
+ variants: Mapping[Key, Transform],
174
+ ) -> dict[Key, str]:
175
+ """
176
+ Build named URLs for one source using complete transformations.
177
+
178
+ Args:
179
+ source: Complete source URI understood by the imgproxy server.
180
+ variants: Names mapped to the transformation for each variant.
181
+ Each transformation is passed unchanged to :meth:`url`.
182
+
183
+ Returns:
184
+ A new dictionary preserving the input keys and iteration order.
185
+ The key type is preserved, including literal string unions.
186
+ An empty mapping produces an empty dictionary.
187
+ No network request is made.
188
+
189
+ """
190
+ return {
191
+ name: self.url(source, transform=transform)
192
+ for name, transform in variants.items()
193
+ }
@@ -0,0 +1,29 @@
1
+ # Optional integrations check their dependencies before importing adapters.
2
+ # flake8: noqa: WPS412
3
+ try: # noqa: RUF067
4
+ import django # noqa: F401 # pyright: ignore[reportUnusedImport]
5
+ except ImportError as exc: # pragma: no cover
6
+ raise ImportError(
7
+ 'The Django integration requires Django. '
8
+ "Install it with `pip install 'imgproxykit[django]'`.",
9
+ ) from exc
10
+
11
+ from imgproxykit.integrations.django.client import get_client as get_client
12
+ from imgproxykit.integrations.django.settings import (
13
+ ClientSettings as ClientSettings,
14
+ )
15
+ from imgproxykit.integrations.django.settings import (
16
+ ClientSettingsDict as ClientSettingsDict,
17
+ )
18
+ from imgproxykit.integrations.django.settings import (
19
+ Settings as Settings,
20
+ )
21
+ from imgproxykit.integrations.django.settings import (
22
+ SettingsDict as SettingsDict,
23
+ )
24
+ from imgproxykit.integrations.django.shortcuts import (
25
+ imgproxy_url as imgproxy_url,
26
+ )
27
+ from imgproxykit.integrations.django.shortcuts import (
28
+ imgproxy_variants as imgproxy_variants,
29
+ )
@@ -0,0 +1,8 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class ImgproxyKitConfig(AppConfig):
5
+ """Django application configuration for imgproxykit."""
6
+
7
+ name = 'imgproxykit.integrations.django'
8
+ label = 'imgproxykit'
@@ -0,0 +1,39 @@
1
+ from functools import lru_cache
2
+ from typing import Any
3
+
4
+ from django.core.signals import setting_changed
5
+ from django.dispatch import receiver
6
+
7
+ from imgproxykit.client import Client
8
+ from imgproxykit.integrations.django.settings import (
9
+ IMGPROXYKIT_SETTINGS,
10
+ ClientSettings,
11
+ Settings,
12
+ get_config,
13
+ )
14
+
15
+
16
+ @lru_cache(maxsize=1)
17
+ def get_client() -> Client:
18
+ """
19
+ Return the cached client configured by IMGPROXYKIT['client'].
20
+
21
+ Create the client on first use. Django's ``override_settings`` clears
22
+ the cache when entering and leaving an override of ``IMGPROXYKIT``.
23
+ """
24
+ config = get_config()[Settings.client.value]
25
+ # Client takes `base_url` positionally;
26
+ # forward the remaining client options.
27
+ options = {
28
+ name: value
29
+ for name, value in config.items()
30
+ if name != ClientSettings.base_url
31
+ }
32
+ return Client(config[ClientSettings.base_url.value], **options) # type: ignore[call-overload, no-any-return] # pyright: ignore[reportCallIssue, reportArgumentType] # ty: ignore[no-matching-overload]
33
+
34
+
35
+ @receiver(setting_changed)
36
+ def _reset_client(*, setting: str, **kwargs: Any) -> None:
37
+ """Discard the cached client when Django overrides IMGPROXYKIT."""
38
+ if setting == IMGPROXYKIT_SETTINGS:
39
+ get_client.cache_clear()
@@ -0,0 +1,115 @@
1
+ import enum
2
+ from collections.abc import Callable, Mapping
3
+ from typing import Any, Final, Required, final
4
+
5
+ from django.core.exceptions import ImproperlyConfigured
6
+ from django.db.models.fields.files import FieldFile
7
+ from typing_extensions import TypedDict
8
+
9
+ from imgproxykit.transform import Transform
10
+
11
+ #: Django setting containing the imgproxy client configuration.
12
+ IMGPROXYKIT_SETTINGS: Final = 'IMGPROXYKIT'
13
+
14
+
15
+ @final
16
+ @enum.unique
17
+ class ClientSettings(enum.StrEnum):
18
+ """Name options in IMGPROXYKIT's client dictionary."""
19
+
20
+ base_url = 'base_url'
21
+ key = 'key'
22
+ salt = 'salt'
23
+ signature_size = 'signature_size'
24
+ unsigned_signature = 'unsigned_signature'
25
+ arguments_separator = 'arguments_separator'
26
+
27
+
28
+ @final
29
+ @enum.unique
30
+ class Settings(enum.StrEnum):
31
+ """Name options in Django's IMGPROXYKIT dictionary."""
32
+
33
+ client = 'client'
34
+ transforms = 'transforms'
35
+ variants = 'variants'
36
+ source_resolver = 'source_resolver'
37
+
38
+
39
+ class ClientSettingsDict(TypedDict, total=False, closed=True):
40
+ """Describe client constructor options for static type checking."""
41
+
42
+ #: Public imgproxy address, including any deployment path prefix.
43
+ base_url: Required[str]
44
+ #: Hex-encoded signing key matching the imgproxy server.
45
+ key: str | None
46
+ #: Hex-encoded signing salt matching the imgproxy server.
47
+ salt: str | None
48
+ #: Positive signature digest byte count; must match the server.
49
+ signature_size: int
50
+ #: Signature marker used when signing credentials are omitted.
51
+ unsigned_signature: str
52
+ #: Processing argument separator; must match the server.
53
+ arguments_separator: str
54
+
55
+
56
+ class SettingsDict(TypedDict, total=False, closed=True):
57
+ """Describe the IMGPROXYKIT dictionary for static type checking."""
58
+
59
+ #: Client constructor options; defaults remain in the core Client.
60
+ client: Required[ClientSettingsDict]
61
+ #: Named Python transformations, distinct from imgproxy server presets.
62
+ transforms: Mapping[str, Transform]
63
+ #: Named sets of transformations; objects can be shared with transforms.
64
+ variants: Mapping[str, Mapping[str, Transform]]
65
+ #: Convert the original source to a URI, including empty file fields.
66
+ source_resolver: Callable[[str | FieldFile], str] | str
67
+
68
+
69
+ assert set(SettingsDict.__annotations__) == set(Settings), ( # noqa: S101
70
+ 'Settings enum and its type SettingsDict have different keys'
71
+ )
72
+ assert set(ClientSettingsDict.__annotations__) == set(ClientSettings), ( # noqa: S101
73
+ 'ClientSettings enum and its type ClientSettingsDict have different keys'
74
+ )
75
+
76
+
77
+ # Client defaults stay in Client; these defaults belong to the Django adapter.
78
+ _DEFAULTS: Final[Mapping[str, Any]] = { # noqa: WPS407
79
+ Settings.transforms: {},
80
+ Settings.variants: {},
81
+ Settings.source_resolver: (
82
+ 'imgproxykit.integrations.django.sources.default_source_resolver'
83
+ ),
84
+ }
85
+
86
+
87
+ def get_config() -> SettingsDict:
88
+ """
89
+ Read the client configuration from Django's IMGPROXYKIT setting.
90
+
91
+ Access settings only when called. Merge adapter defaults with supplied
92
+ settings without modifying the original dictionary. Client option
93
+ defaults and signing validation remain in the core client.
94
+
95
+ Returns:
96
+ A new dictionary containing adapter defaults and configured options.
97
+
98
+ Raises:
99
+ ImproperlyConfigured: If ``IMGPROXYKIT`` is missing or ``None``.
100
+
101
+ """
102
+ # Keep LazySettings out of module globals: doctest inspection evaluates it.
103
+ from django.conf import settings # noqa: PLC0415
104
+
105
+ config = getattr(settings, IMGPROXYKIT_SETTINGS, None)
106
+ if config is None:
107
+ raise ImproperlyConfigured(
108
+ 'Define IMGPROXYKIT in Django settings to configure imgproxykit.',
109
+ )
110
+ return _resolve_defaults(config) # type: ignore[no-any-return]
111
+
112
+
113
+ def _resolve_defaults(config: Mapping[str, Any]) -> Any:
114
+ """Overlay configured options on the Django adapter defaults."""
115
+ return {**_DEFAULTS, **config}
@@ -0,0 +1,79 @@
1
+ from collections.abc import Mapping
2
+ from typing import overload
3
+
4
+ from django.db.models.fields.files import FieldFile
5
+
6
+ from imgproxykit.integrations.django.client import get_client
7
+ from imgproxykit.integrations.django.settings import Settings, get_config
8
+ from imgproxykit.integrations.django.sources import resolve_source
9
+ from imgproxykit.transform import Transform
10
+
11
+
12
+ def imgproxy_url(
13
+ source: str | FieldFile,
14
+ transform: Transform | str | None = None,
15
+ ) -> str:
16
+ """
17
+ Build an imgproxy URL using Django's configured client.
18
+
19
+ Args:
20
+ source: Source URI or model file field, passed to the source resolver.
21
+ transform: Transformation or name from ``IMGPROXYKIT['transforms']``.
22
+ Omit to add no processing options.
23
+
24
+ Returns:
25
+ Image URL.
26
+
27
+ Raises:
28
+ KeyError: If a named transformation is not configured.
29
+ ValueError: If the default source resolver receives an empty file field.
30
+
31
+ """
32
+ if isinstance(transform, str):
33
+ transform = get_config()[Settings.transforms.value][transform] # pyright: ignore[reportTypedDictNotRequiredAccess]
34
+ return get_client().url(resolve_source(source), transform=transform)
35
+
36
+
37
+ @overload
38
+ def imgproxy_variants[Key: str](
39
+ source: str | FieldFile,
40
+ variants: Mapping[Key, Transform],
41
+ ) -> dict[Key, str]: ...
42
+
43
+
44
+ @overload
45
+ def imgproxy_variants(
46
+ source: str | FieldFile,
47
+ variants: str,
48
+ ) -> dict[str, str]: ...
49
+
50
+
51
+ def imgproxy_variants[Key: str](
52
+ source: str | FieldFile,
53
+ variants: Mapping[Key, Transform] | str,
54
+ ) -> dict[Key, str] | dict[str, str]:
55
+ """
56
+ Build named image URLs using Django's configured client.
57
+
58
+ Args:
59
+ source: Source URI or model file field, resolved once for all variants.
60
+ variants: Transformation mapping or set name from
61
+ ``IMGPROXYKIT['variants']``.
62
+
63
+ Returns:
64
+ URLs in variant order. Direct mappings preserve their key type.
65
+
66
+ Raises:
67
+ KeyError: If a named variant set is not configured.
68
+ ValueError: If the default source resolver receives an empty file field.
69
+
70
+ """
71
+ client = get_client()
72
+
73
+ # Resolve the source inside each branch so named sets are looked up first.
74
+ # Only one branch runs, so the resolver is called once per invocation.
75
+ if not isinstance(variants, str):
76
+ return client.variants(resolve_source(source), variants=variants)
77
+
78
+ configured = get_config()[Settings.variants.value][variants] # pyright: ignore[reportTypedDictNotRequiredAccess]
79
+ return client.variants(resolve_source(source), variants=configured)