imgproxykit 0.3.0__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 (72) hide show
  1. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/PKG-INFO +60 -51
  2. imgproxykit-0.4.0/README.md +111 -0
  3. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/client.py +27 -0
  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.4.0/imgproxykit/py.typed +0 -0
  15. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/transform.py +0 -7
  16. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/pyproject.toml +37 -13
  17. imgproxykit-0.3.0/README.md +0 -106
  18. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/LICENSE +0 -0
  19. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/__init__.py +0 -0
  20. {imgproxykit-0.3.0/imgproxykit/internal → imgproxykit-0.4.0/imgproxykit/integrations}/__init__.py +0 -0
  21. /imgproxykit-0.3.0/imgproxykit/py.typed → /imgproxykit-0.4.0/imgproxykit/integrations/django/templatetags/__init__.py +0 -0
  22. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/internal/encoding.py +0 -0
  23. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/__init__.py +0 -0
  24. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/auto_rotate.py +0 -0
  25. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/background.py +0 -0
  26. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/base.py +0 -0
  27. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/blur.py +0 -0
  28. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/cache_buster.py +0 -0
  29. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/crop.py +0 -0
  30. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/dpr.py +0 -0
  31. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/enforce_thumbnail.py +0 -0
  32. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/enlarge.py +0 -0
  33. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/expires.py +0 -0
  34. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/extend.py +0 -0
  35. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/extend_aspect_ratio.py +0 -0
  36. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/filename.py +0 -0
  37. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/flip.py +0 -0
  38. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/format.py +0 -0
  39. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/format_quality.py +0 -0
  40. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/gravity.py +0 -0
  41. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/height.py +0 -0
  42. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/keep_copyright.py +0 -0
  43. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/max_animation_frame_resolution.py +0 -0
  44. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/max_animation_frames.py +0 -0
  45. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/max_bytes.py +0 -0
  46. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/max_result_dimension.py +0 -0
  47. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/max_src_file_size.py +0 -0
  48. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/max_src_resolution.py +0 -0
  49. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/min_height.py +0 -0
  50. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/min_width.py +0 -0
  51. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/padding.py +0 -0
  52. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/pixelate.py +0 -0
  53. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/preserve_hdr.py +0 -0
  54. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/preset.py +0 -0
  55. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/quality.py +0 -0
  56. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/raw.py +0 -0
  57. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/resize.py +0 -0
  58. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/resizing_type.py +0 -0
  59. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/return_attachment.py +0 -0
  60. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/rotate.py +0 -0
  61. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/sharpen.py +0 -0
  62. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/size.py +0 -0
  63. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/skip_processing.py +0 -0
  64. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/strip_color_profile.py +0 -0
  65. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/strip_metadata.py +0 -0
  66. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/trim.py +0 -0
  67. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/watermark.py +0 -0
  68. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/width.py +0 -0
  69. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/options/zoom.py +0 -0
  70. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/serialization.py +0 -0
  71. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/signing.py +0 -0
  72. {imgproxykit-0.3.0 → imgproxykit-0.4.0}/imgproxykit/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: imgproxykit
3
- Version: 0.3.0
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,77 +49,82 @@ 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
- # Public URL of your imgproxy server.
71
- client = Client('https://imgproxy.example.com')
72
-
73
- thumbnail = Transform(
74
- Resize(width=300, height=300, mode='fill'), # Pass typed option objects.
75
- Gravity(position='sm'), # Let imgproxy choose the crop's focus.
76
- quality=80, # Or scalar keywords, equivalent to Quality(80).
77
- format='webp',
78
- )
79
- source_urls = [
80
- 'https://originals.example.com/products/backpack.jpg',
81
- 'https://originals.example.com/products/sneakers.jpg',
82
- ]
83
- # Reuse one immutable transformation across your catalog.
84
- thumbnail_urls = [
85
- client.url(source=source_url, transform=thumbnail)
86
- for source_url in source_urls
87
- ]
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
+
88
90
  ```
89
91
 
90
- Use these URLs in your images' `src` attributes. Building a URL makes no
91
- network requests: when a browser requests it, imgproxy fetches the original
92
- image from `originals.example.com` and processes it.
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
93
96
 
94
- Sign URLs and reuse presets configured on your imgproxy server:
97
+ Build variants by combining shared settings with different sizes:
95
98
 
96
99
  ```python
97
- from imgproxykit import Client, Transform
98
- from imgproxykit.options import Preset
99
-
100
- client = Client(
101
- 'https://imgproxy.example.com',
102
- # Replace with your imgproxy server's hex-encoded key and salt.
103
- key='736563726574',
104
- salt='73616c74',
105
- )
106
-
107
- thumbnail = Transform(
108
- Preset('product-card'), # Reuse a preset from your imgproxy server.
109
- format='webp', # Combine server presets with explicit processing options.
110
- )
111
- source_url = 'https://originals.example.com/products/backpack.jpg'
112
- # The client signs the URL using your server's key and salt.
113
- thumbnail_url = client.url(source=source_url, transform=thumbnail)
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
+
114
117
  ```
115
118
 
116
- See the [full documentation](https://imgproxykit.readthedocs.io/en/latest/)
117
- for client configuration, transformations, and processing options.
118
- Find published releases on [PyPI](https://pypi.org/project/imgproxykit/).
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/).
119
128
 
120
129
  ## Contributing
121
130
 
@@ -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
@@ -164,3 +165,29 @@ class Client:
164
165
  path = self._path_serializer(source, transform=transform)
165
166
  signature = self._url_signer(path)
166
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)
@@ -0,0 +1,44 @@
1
+ from django.db.models.fields.files import FieldFile
2
+ from django.utils.module_loading import import_string
3
+
4
+ from imgproxykit.integrations.django.settings import Settings, get_config
5
+
6
+
7
+ def resolve_source(source: str | FieldFile) -> str:
8
+ """
9
+ Resolve an image source using Django's configured resolver.
10
+
11
+ Call ``source_resolver`` with the original string or file field. The
12
+ setting accepts a callable or a dotted import path to one. It must
13
+ return a URI understood by the imgproxy server.
14
+ This allows projects to resolve relative media URLs or construct storage
15
+ URIs such as ``s3://bucket/key`` without accessing the field's URL first.
16
+
17
+ Without a resolver, return strings unchanged and use ``FieldFile.url``
18
+ for file fields. Relative URLs are not expanded automatically.
19
+
20
+ Args:
21
+ source: Source string or model file field, including empty fields.
22
+
23
+ Returns:
24
+ Source URI to pass to the configured client.
25
+
26
+ """
27
+ resolver = get_config()[Settings.source_resolver.value] # pyright: ignore[reportTypedDictNotRequiredAccess]
28
+ if isinstance(resolver, str):
29
+ resolver = import_string(resolver)
30
+ return resolver(source)
31
+
32
+
33
+ def default_source_resolver(source: str | FieldFile) -> str:
34
+ """
35
+ Return a source string unchanged or use a file field's storage URL.
36
+
37
+ Relative URLs are not expanded.
38
+
39
+ Raises:
40
+ ValueError: If the file field has no associated file, as with
41
+ direct access to ``FieldFile.url``.
42
+
43
+ """
44
+ return source.url if isinstance(source, FieldFile) else source
@@ -0,0 +1,12 @@
1
+ from django import template
2
+
3
+ from imgproxykit.integrations.django.shortcuts import (
4
+ imgproxy_url,
5
+ imgproxy_variants,
6
+ )
7
+
8
+ register = template.Library()
9
+
10
+ # Keep URL generation shared with Python callers; simple_tag handles escaping.
11
+ register.simple_tag(imgproxy_url)
12
+ register.simple_tag(imgproxy_variants)
@@ -0,0 +1,13 @@
1
+ # Optional integrations check their dependencies before importing adapters.
2
+ # flake8: noqa: WPS412
3
+ try: # noqa: RUF067
4
+ import fastapi # noqa: F401 # pyright: ignore[reportUnusedImport]
5
+ except ImportError as exc: # pragma: no cover
6
+ raise ImportError(
7
+ 'The FastAPI integration requires FastAPI. '
8
+ "Install it with `pip install 'imgproxykit[fastapi]'`.",
9
+ ) from exc
10
+
11
+ from imgproxykit.integrations.fastapi.dependencies import (
12
+ add_imgproxy as add_imgproxy,
13
+ )
@@ -0,0 +1,53 @@
1
+ from collections.abc import Awaitable, Callable
2
+
3
+ from fastapi import FastAPI, Request
4
+
5
+ from imgproxykit.client import Client
6
+
7
+
8
+ def add_imgproxy(
9
+ app: FastAPI,
10
+ client: Client,
11
+ *,
12
+ name: str = 'imgproxykit_client',
13
+ ) -> Callable[[Request], Awaitable[Client]]:
14
+ """
15
+ Register a client and return its FastAPI dependency.
16
+
17
+ Call while building the application, before it starts serving requests.
18
+ Keep the returned callable for use with ``Depends`` and dependency
19
+ overrides. Each application owns its clients; the dependency resolves
20
+ its name against the application handling the current request.
21
+
22
+ Args:
23
+ app: Application that owns the client.
24
+ client: Configured URL builder, including any signing credentials.
25
+ name: Attribute name on ``app.state``. Defaults to
26
+ ``'imgproxykit_client'``. Must not already exist.
27
+
28
+ Returns:
29
+ An async dependency returning the registered client. URL generation
30
+ remains synchronous and makes no network requests.
31
+
32
+ Raises:
33
+ ValueError: If the application's state already has this attribute.
34
+ TypeError: When the application's state attribute does not contain
35
+ a client, including when it has not been registered.
36
+ """
37
+ if hasattr(app.state, name):
38
+ raise ValueError(
39
+ f'Application state already has an attribute named {name!r}.',
40
+ )
41
+ setattr(app.state, name, client)
42
+
43
+ # FastAPI awaits this in place instead of scheduling a thread-pool call.
44
+ async def get_imgproxy(request: Request) -> Client: # noqa: RUF029, WPS430
45
+ registered = getattr(request.app.state, name, None)
46
+ if not isinstance(registered, Client):
47
+ raise TypeError(
48
+ f'No imgproxy client named {name!r} is registered on this '
49
+ 'application. Call add_imgproxy(app, client, name=...) first.',
50
+ )
51
+ return registered
52
+
53
+ return get_imgproxy
File without changes
File without changes
@@ -63,13 +63,6 @@ class Transform:
63
63
 
64
64
  """
65
65
 
66
- # TODO: Add immutable derivation with explicit append/replace/remove
67
- # semantics. Define conflicts between overlapping options (Resize, Size,
68
- # Width, Height), repeated options, and server presets without expanding
69
- # preset definitions locally. Support clearing inherited options to
70
- # restore server defaults.
71
- # TODO: Document with examples that option order controls serialization
72
- # and overrides, while imgproxy determines the processing pipeline.
73
66
  options: tuple[Option, ...]
74
67
 
75
68
  def __init__(
@@ -5,7 +5,7 @@ requires = [ "poetry-core>=2" ]
5
5
 
6
6
  [project]
7
7
  name = "imgproxykit"
8
- version = "0.3.0"
8
+ version = "0.4.0"
9
9
  description = "A typed Python toolkit for building imgproxy URLs"
10
10
  readme = "README.md"
11
11
  keywords = [
@@ -22,6 +22,10 @@ dependencies = [
22
22
  "typing-extensions>=4.16,<5",
23
23
  ]
24
24
 
25
+ [project.optional-dependencies]
26
+ django = [ "django>=5.2,<7" ]
27
+ fastapi = [ "fastapi>=0.135.2,<1" ]
28
+
25
29
  [[project.authors]]
26
30
  name = "Alexander Kondratev"
27
31
  email = "mail@kondratev.dev"
@@ -45,24 +49,39 @@ classifiers = [
45
49
  ]
46
50
 
47
51
  [tool.poetry.group.dev.dependencies]
48
- covdefaults = "^2.3"
52
+ # Linting and architecture checks:
49
53
  import-linter = ">=2.5,<3"
50
- inline-snapshot = ">=0.35,<1"
54
+ ruff = "^0.17"
55
+ slotscheck = ">=0.19,<0.22"
56
+ wemake-python-styleguide = "^1.8"
57
+
58
+ # Static type checking:
51
59
  mypy = "^2.4"
52
60
  pyrefly = ">=1,<2"
53
61
  pyright = ">=1.1,<2"
54
62
  # TODO: relax the pin after a stable `ty` release:
55
- ty = "==0.0.87"
63
+ ty = "==0.0.88"
64
+
65
+ # Unit tests, snapshots, and coverage:
66
+ covdefaults = "^2.3"
67
+ faker = ">=37,<41"
68
+ inline-snapshot = ">=0.35,<1"
56
69
  pytest = "^9.1"
70
+ pytest-asyncio = ">=1.3,<2"
57
71
  pytest-cov = "^7.1"
58
72
  pytest-randomly = "^5.0"
59
- ruff = "^0.17"
60
- slotscheck = ">=0.19,<0.22"
61
- wemake-python-styleguide = "^1.8"
62
- testcontainers = ">=4.15,<5"
73
+
74
+ # Integration tests and image assertions:
63
75
  pillow = ">=12,<13"
76
+ testcontainers = ">=4.15,<5"
64
77
  zapros = ">=0.21,<0.22"
65
- faker = ">=37,<41"
78
+
79
+ # Django integration typing and tests:
80
+ django-stubs = "^6.1.2"
81
+ pytest-django = ">=4.12,<5"
82
+
83
+ # FastAPI test application server:
84
+ uvicorn = "^0.54"
66
85
 
67
86
  [tool.poetry.group.docs]
68
87
  optional = true
@@ -218,7 +237,7 @@ strict = true
218
237
 
219
238
 
220
239
  [tool.pyrefly]
221
- project-includes = [ "imgproxykit", "tests", "docs/examples" ]
240
+ project-includes = [ "imgproxykit", "tests", "test_apps", "docs/examples" ]
222
241
  min-severity = "warn"
223
242
  preset = "strict"
224
243
 
@@ -234,7 +253,7 @@ pythonVersion = "3.12"
234
253
  venv = ".venv"
235
254
  venvPath = "."
236
255
  typeCheckingMode = "strict"
237
- include = [ "imgproxykit", "tests", "docs/examples" ]
256
+ include = [ "imgproxykit", "tests", "test_apps", "docs/examples" ]
238
257
  enableTypeIgnoreComments = false
239
258
  reportUnnecessaryTypeIgnoreComment = "error"
240
259
 
@@ -247,7 +266,7 @@ reportPrivateUsage = false
247
266
 
248
267
  [tool.ty.src]
249
268
  # Docs: https://docs.astral.sh/ty/reference/configuration
250
- include = [ "imgproxykit", "tests", "docs/examples" ]
269
+ include = [ "imgproxykit", "tests", "test_apps", "docs/examples" ]
251
270
 
252
271
  [tool.ty.analysis]
253
272
  strict-literal-narrowing = true
@@ -257,6 +276,7 @@ respect-type-ignore-comments = false
257
276
 
258
277
 
259
278
  [tool.pytest.ini_options]
279
+ pythonpath = [ "test_apps/django" ]
260
280
  addopts = [
261
281
  "--strict-config",
262
282
  "--strict-markers",
@@ -282,7 +302,11 @@ addopts = [
282
302
  xfail_strict = true
283
303
  # Fail on warnings:
284
304
  filterwarnings = [ "error" ]
285
-
305
+ # pytest-asyncio configuration:
306
+ # https://pytest-asyncio.readthedocs.io/en/stable/reference/configuration.html
307
+ asyncio_mode = "auto"
308
+ # Django settings:
309
+ DJANGO_SETTINGS_MODULE = "server.settings"
286
310
 
287
311
  [tool.coverage.run]
288
312
  # Covdefaults: https://pypi.org/project/covdefaults
@@ -1,106 +0,0 @@
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] Expressive transforms: combine option objects with concise scalar arguments
21
- - [x] Immutable, reusable transforms for consistent image settings across your app
22
- - [x] Support for named presets configured on your imgproxy server
23
-
24
- ---------
25
-
26
- ## Installation
27
-
28
- Requires **Python 3.12+** and a running imgproxy server.
29
-
30
- ```bash
31
- pip install imgproxykit
32
- ```
33
-
34
- ## Example
35
-
36
- Define a WebP thumbnail once and reuse it across a product catalog:
37
-
38
- ```python
39
- from imgproxykit import Client, Transform
40
- from imgproxykit.options import Gravity, Resize
41
-
42
- # Public URL of your imgproxy server.
43
- client = Client('https://imgproxy.example.com')
44
-
45
- thumbnail = Transform(
46
- Resize(width=300, height=300, mode='fill'), # Pass typed option objects.
47
- Gravity(position='sm'), # Let imgproxy choose the crop's focus.
48
- quality=80, # Or scalar keywords, equivalent to Quality(80).
49
- format='webp',
50
- )
51
- source_urls = [
52
- 'https://originals.example.com/products/backpack.jpg',
53
- 'https://originals.example.com/products/sneakers.jpg',
54
- ]
55
- # Reuse one immutable transformation across your catalog.
56
- thumbnail_urls = [
57
- client.url(source=source_url, transform=thumbnail)
58
- for source_url in source_urls
59
- ]
60
- ```
61
-
62
- Use these URLs in your images' `src` attributes. Building a URL makes no
63
- network requests: when a browser requests it, imgproxy fetches the original
64
- image from `originals.example.com` and processes it.
65
-
66
- Sign URLs and reuse presets configured on your imgproxy server:
67
-
68
- ```python
69
- from imgproxykit import Client, Transform
70
- from imgproxykit.options import Preset
71
-
72
- client = Client(
73
- 'https://imgproxy.example.com',
74
- # Replace with your imgproxy server's hex-encoded key and salt.
75
- key='736563726574',
76
- salt='73616c74',
77
- )
78
-
79
- thumbnail = Transform(
80
- Preset('product-card'), # Reuse a preset from your imgproxy server.
81
- format='webp', # Combine server presets with explicit processing options.
82
- )
83
- source_url = 'https://originals.example.com/products/backpack.jpg'
84
- # The client signs the URL using your server's key and salt.
85
- thumbnail_url = client.url(source=source_url, transform=thumbnail)
86
- ```
87
-
88
- See the [full documentation](https://imgproxykit.readthedocs.io/en/latest/)
89
- for client configuration, transformations, and processing options.
90
- Find published releases on [PyPI](https://pypi.org/project/imgproxykit/).
91
-
92
- ## Contributing
93
-
94
- See the [contributing guide](CONTRIBUTING.md) for development setup and checks.
95
- Bug reports and feature requests are welcome on the
96
- [issue tracker](https://github.com/kondratevdev/imgproxykit/issues).
97
-
98
- ## License
99
-
100
- [MIT](LICENSE)
101
-
102
- ## Credits
103
-
104
- Generated with
105
- [`wemake-python-package`](https://github.com/wemake-services/wemake-python-package)
106
- ([template version](https://github.com/wemake-services/wemake-python-package/tree/47d9dddd29da8d6d3d1a403f8a143b323a812083)).
File without changes