django-smart-ratelimit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be added to the global gitignore or merged into this project gitignore. For a PyCharm
158
+ # project, it is recommended to ignore .idea/ directory.
159
+ .idea/
160
+
161
+ # VS Code
162
+ .vscode/
163
+
164
+ # macOS
165
+ .DS_Store
166
+ .DS_Store?
167
+ ._*
168
+ .Spotlight-V100
169
+ .Trashes
170
+ ehthumbs.db
171
+ Thumbs.db
172
+
173
+ # Windows
174
+ Thumbs.db
175
+ ehthumbs.db
176
+ Desktop.ini
177
+ $RECYCLE.BIN/
178
+
179
+ # Linux
180
+ *~
181
+
182
+ # Project specific
183
+ test_db.sqlite3
184
+ *.db
185
+ *.sqlite
186
+ *.sqlite3
187
+
188
+ # Backup files
189
+ *.bak
190
+ *.backup
191
+ *.old
192
+ *.orig
193
+
194
+ # Temporary files
195
+ *.tmp
196
+ *.temp
197
+ .tmp/
198
+ .temp/
199
+
200
+ # Log files
201
+ *.log
202
+ *.out
203
+ *.err
204
+
205
+ # Redis dump
206
+ dump.rdb
207
+
208
+ # Coverage reports
209
+ htmlcov/
210
+ coverage/
211
+ .coverage
212
+ .coverage.*
213
+ coverage.xml
214
+ *.cover
215
+ .hypothesis/
216
+ .pytest_cache/
217
+
218
+ # Documentation builds
219
+ docs/_build/
220
+ docs/build/
221
+ site/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yasser Shkeir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,402 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-smart-ratelimit
3
+ Version: 0.1.0
4
+ Summary: A flexible and efficient rate limiting library for Django applications
5
+ Project-URL: Homepage, https://github.com/YasserShkeir/django-smart-ratelimit
6
+ Project-URL: Documentation, https://django-smart-ratelimit.readthedocs.io
7
+ Project-URL: Repository, https://github.com/YasserShkeir/django-smart-ratelimit
8
+ Project-URL: Issues, https://github.com/YasserShkeir/django-smart-ratelimit/issues
9
+ Project-URL: Changelog, https://github.com/YasserShkeir/django-smart-ratelimit/blob/main/CHANGELOG.md
10
+ Author-email: Yasser Shkeir <shkeiryasser@gmail.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: decorator,django,middleware,rate-limiting,redis
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 3.2
17
+ Classifier: Framework :: Django :: 4.0
18
+ Classifier: Framework :: Django :: 4.1
19
+ Classifier: Framework :: Django :: 4.2
20
+ Classifier: Framework :: Django :: 5.0
21
+ Classifier: Intended Audience :: Developers
22
+ Classifier: License :: OSI Approved :: MIT License
23
+ Classifier: Operating System :: OS Independent
24
+ Classifier: Programming Language :: Python
25
+ Classifier: Programming Language :: Python :: 3
26
+ Classifier: Programming Language :: Python :: 3.9
27
+ Classifier: Programming Language :: Python :: 3.10
28
+ Classifier: Programming Language :: Python :: 3.11
29
+ Classifier: Programming Language :: Python :: 3.12
30
+ Classifier: Topic :: Internet :: WWW/HTTP
31
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
32
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
33
+ Classifier: Topic :: System :: Systems Administration
34
+ Requires-Python: >=3.9
35
+ Requires-Dist: django>=3.2
36
+ Requires-Dist: redis>=4.0
37
+ Provides-Extra: dev
38
+ Requires-Dist: bandit>=1.7; extra == 'dev'
39
+ Requires-Dist: black>=22.0; extra == 'dev'
40
+ Requires-Dist: build>=0.8; extra == 'dev'
41
+ Requires-Dist: django-stubs>=4.0; extra == 'dev'
42
+ Requires-Dist: flake8-docstrings>=1.7; extra == 'dev'
43
+ Requires-Dist: flake8>=5.0; extra == 'dev'
44
+ Requires-Dist: isort>=5.0; extra == 'dev'
45
+ Requires-Dist: mypy>=1.0; extra == 'dev'
46
+ Requires-Dist: pre-commit>=2.20; extra == 'dev'
47
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
48
+ Requires-Dist: pytest-django>=4.5; extra == 'dev'
49
+ Requires-Dist: pytest>=7.0; extra == 'dev'
50
+ Requires-Dist: safety>=2.0; extra == 'dev'
51
+ Requires-Dist: twine>=4.0; extra == 'dev'
52
+ Requires-Dist: types-redis>=4.0; extra == 'dev'
53
+ Description-Content-Type: text/markdown
54
+
55
+ # Django Smart Ratelimit
56
+
57
+ [![CI](https://github.com/YasserShkeir/django-smart-ratelimit/workflows/CI/badge.svg)](https://github.com/YasserShkeir/django-smart-ratelimit/actions)
58
+ [![PyPI version](https://badge.fury.io/py/django-smart-ratelimit.svg)](https://badge.fury.io/py/django-smart-ratelimit)
59
+ [![Python versions](https://img.shields.io/pypi/pyversions/django-smart-ratelimit.svg)](https://pypi.org/project/django-smart-ratelimit/)
60
+ [![Django versions](https://img.shields.io/pypi/djversions/django-smart-ratelimit.svg)](https://pypi.org/project/django-smart-ratelimit/)
61
+
62
+ A flexible and efficient rate limiting library for Django applications with support for multiple backends and sliding window algorithms.
63
+
64
+ ## Features
65
+
66
+ - 🚀 **High Performance**: Atomic operations using Redis Lua scripts
67
+ - 🔧 **Flexible Configuration**: Both decorator and middleware support
68
+ - 🪟 **Multiple Algorithms**: Fixed window and sliding window rate limiting
69
+ - 🔌 **Multiple Backends**: Redis backend with extensible architecture
70
+ - 📊 **Rich Headers**: Standard rate limiting headers
71
+ - 🛡️ **Production Ready**: Comprehensive testing and error handling
72
+
73
+ ## Quick Start
74
+
75
+ ### Installation
76
+
77
+ ```bash
78
+ pip install django-smart-ratelimit
79
+ ```
80
+
81
+ ### Basic Usage
82
+
83
+ #### Decorator Style
84
+
85
+ ```python
86
+ from django_smart_ratelimit import rate_limit
87
+
88
+ @rate_limit(key='ip', rate='10/m')
89
+ def my_view(request):
90
+ return HttpResponse('Hello World')
91
+
92
+ @rate_limit(key='user:{user.id}', rate='100/h', block=True)
93
+ def api_endpoint(request):
94
+ return JsonResponse({'data': 'some data'})
95
+ ```
96
+
97
+ #### Middleware Style
98
+
99
+ ```python
100
+ # settings.py
101
+ MIDDLEWARE = [
102
+ 'django_smart_ratelimit.middleware.RateLimitMiddleware',
103
+ # ... other middleware
104
+ ]
105
+
106
+ RATELIMIT_MIDDLEWARE = {
107
+ 'DEFAULT_RATE': '100/m',
108
+ 'BACKEND': 'redis',
109
+ 'SKIP_PATHS': ['/admin/', '/health/'],
110
+ 'RATE_LIMITS': {
111
+ '/api/': '1000/h',
112
+ '/auth/login/': '5/m',
113
+ }
114
+ }
115
+ ```
116
+
117
+ ### Configuration
118
+
119
+ #### Redis Backend
120
+
121
+ ```python
122
+ # settings.py
123
+ RATELIMIT_BACKEND = 'redis'
124
+ RATELIMIT_REDIS = {
125
+ 'host': 'localhost',
126
+ 'port': 6379,
127
+ 'db': 0,
128
+ 'password': None,
129
+ }
130
+
131
+ # Algorithm selection
132
+ RATELIMIT_USE_SLIDING_WINDOW = True # or False for fixed window
133
+ ```
134
+
135
+ ## Usage Examples
136
+
137
+ ### Decorator Examples
138
+
139
+ #### Basic Rate Limiting
140
+
141
+ ```python
142
+ from django_smart_ratelimit import rate_limit
143
+
144
+ # Limit by IP address
145
+ @rate_limit(key='ip', rate='10/m')
146
+ def public_api(request):
147
+ return JsonResponse({'message': 'Hello World'})
148
+
149
+ # Limit by user
150
+ @rate_limit(key='user', rate='100/h')
151
+ def user_api(request):
152
+ return JsonResponse({'user_data': '...'})
153
+ ```
154
+
155
+ #### Custom Key Functions
156
+
157
+ ```python
158
+ def custom_key(request):
159
+ if request.user.is_authenticated:
160
+ return f"user:{request.user.id}"
161
+ return f"ip:{request.META.get('REMOTE_ADDR')}"
162
+
163
+ @rate_limit(key=custom_key, rate='50/m')
164
+ def smart_api(request):
165
+ return JsonResponse({'data': '...'})
166
+ ```
167
+
168
+ #### Non-blocking Rate Limiting
169
+
170
+ ```python
171
+ @rate_limit(key='ip', rate='10/m', block=False)
172
+ def api_with_headers(request):
173
+ # This will add headers but not block requests
174
+ return JsonResponse({'data': '...'})
175
+ ```
176
+
177
+ ### Middleware Examples
178
+
179
+ #### Path-based Rate Limiting
180
+
181
+ ```python
182
+ RATELIMIT_MIDDLEWARE = {
183
+ 'DEFAULT_RATE': '100/m',
184
+ 'RATE_LIMITS': {
185
+ '/api/public/': '1000/h',
186
+ '/api/private/': '100/h',
187
+ '/auth/': '5/m',
188
+ '/upload/': '10/h',
189
+ }
190
+ }
191
+ ```
192
+
193
+ #### Custom Key Functions
194
+
195
+ ```python
196
+ # utils.py
197
+ def user_key_function(request):
198
+ if request.user.is_authenticated:
199
+ return f"user:{request.user.id}"
200
+ return f"ip:{request.META.get('REMOTE_ADDR')}"
201
+
202
+ def api_key_function(request):
203
+ api_key = request.META.get('HTTP_X_API_KEY')
204
+ if api_key:
205
+ return f"api_key:{api_key}"
206
+ return f"ip:{request.META.get('REMOTE_ADDR')}"
207
+
208
+ # settings.py
209
+ RATELIMIT_MIDDLEWARE = {
210
+ 'KEY_FUNCTION': 'myapp.utils.user_key_function',
211
+ 'RATE_LIMITS': {
212
+ '/api/': '1000/h',
213
+ }
214
+ }
215
+ ```
216
+
217
+ ## Rate Formats
218
+
219
+ The library supports several rate formats:
220
+
221
+ - `10/s` - 10 requests per second
222
+ - `100/m` - 100 requests per minute
223
+ - `1000/h` - 1000 requests per hour
224
+ - `10000/d` - 10000 requests per day
225
+
226
+ ## Response Headers
227
+
228
+ When rate limiting is applied, the following headers are added:
229
+
230
+ ```
231
+ X-RateLimit-Limit: 100
232
+ X-RateLimit-Remaining: 75
233
+ X-RateLimit-Reset: 1640995200
234
+ ```
235
+
236
+ ## Algorithms
237
+
238
+ ### Fixed Window
239
+
240
+ Simple and memory-efficient algorithm that resets the counter at fixed intervals.
241
+
242
+ **Pros:**
243
+
244
+ - Low memory usage
245
+ - Simple implementation
246
+ - Predictable reset times
247
+
248
+ **Cons:**
249
+
250
+ - Potential for burst traffic
251
+ - Less accurate limiting
252
+
253
+ ### Sliding Window
254
+
255
+ More accurate algorithm that maintains a sliding window of requests.
256
+
257
+ **Pros:**
258
+
259
+ - Accurate rate limiting
260
+ - No burst traffic issues
261
+ - Smooth rate limiting
262
+
263
+ **Cons:**
264
+
265
+ - Higher memory usage
266
+ - More complex implementation
267
+
268
+ ## Configuration Reference
269
+
270
+ ### Decorator Parameters
271
+
272
+ | Parameter | Type | Default | Description |
273
+ | --------- | ------------------- | -------- | ------------------------------------- |
274
+ | `key` | `str` or `callable` | Required | Rate limit key or key function |
275
+ | `rate` | `str` | Required | Rate limit (e.g., '10/m') |
276
+ | `block` | `bool` | `True` | Block requests when limit exceeded |
277
+ | `backend` | `str` | `None` | Backend to use (uses default if None) |
278
+
279
+ ### Middleware Settings
280
+
281
+ | Setting | Type | Default | Description |
282
+ | -------------- | ------ | --------- | ---------------------------------- |
283
+ | `DEFAULT_RATE` | `str` | `'100/m'` | Default rate limit |
284
+ | `BACKEND` | `str` | `'redis'` | Backend to use |
285
+ | `KEY_FUNCTION` | `str` | `None` | Import path to key function |
286
+ | `BLOCK` | `bool` | `True` | Block requests when limit exceeded |
287
+ | `SKIP_PATHS` | `list` | `[]` | Paths to skip rate limiting |
288
+ | `RATE_LIMITS` | `dict` | `{}` | Path-specific rate limits |
289
+
290
+ ### Backend Settings
291
+
292
+ | Setting | Type | Default | Description |
293
+ | ------------------------------ | ------ | -------------- | ---------------------------- |
294
+ | `RATELIMIT_BACKEND` | `str` | `'redis'` | Backend to use |
295
+ | `RATELIMIT_REDIS` | `dict` | `{}` | Redis configuration |
296
+ | `RATELIMIT_USE_SLIDING_WINDOW` | `bool` | `True` | Use sliding window algorithm |
297
+ | `RATELIMIT_KEY_PREFIX` | `str` | `'ratelimit:'` | Redis key prefix |
298
+
299
+ ## Development
300
+
301
+ ### Running Tests
302
+
303
+ ```bash
304
+ # Install development dependencies
305
+ pip install -e .[dev]
306
+
307
+ # Run tests
308
+ pytest
309
+
310
+ # Run tests with coverage
311
+ pytest --cov=django_smart_ratelimit --cov-report=html
312
+
313
+ # Run specific test file
314
+ pytest tests/test_decorator.py
315
+ ```
316
+
317
+ ### Code Quality
318
+
319
+ ```bash
320
+ # Format code
321
+ black django_smart_ratelimit tests
322
+
323
+ # Check linting
324
+ flake8 django_smart_ratelimit tests
325
+
326
+ # Type checking
327
+ mypy django_smart_ratelimit
328
+ ```
329
+
330
+ ### Pre-commit Hooks
331
+
332
+ ```bash
333
+ # Install pre-commit hooks
334
+ pre-commit install
335
+
336
+ # Run hooks manually
337
+ pre-commit run --all-files
338
+ ```
339
+
340
+ ## Contributing
341
+
342
+ We welcome contributions! Please follow these steps:
343
+
344
+ 1. Fork the repository
345
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
346
+ 3. Make your changes
347
+ 4. Add tests for your changes
348
+ 5. Run the test suite (`pytest`)
349
+ 6. Commit your changes (`git commit -m 'Add amazing feature'`)
350
+ 7. Push to the branch (`git push origin feature/amazing-feature`)
351
+ 8. Open a Pull Request
352
+
353
+ ### Contribution Guidelines
354
+
355
+ - Write tests for new features
356
+ - Follow the existing code style
357
+ - Add docstrings to new functions and classes
358
+ - Update documentation as needed
359
+ - Add type hints where appropriate
360
+
361
+ ## License
362
+
363
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
364
+
365
+ ## Changelog
366
+
367
+ ### v0.1.0 (Initial Release)
368
+
369
+ - Basic decorator and middleware support
370
+ - Redis backend with sliding window algorithm
371
+ - Comprehensive test suite
372
+ - Documentation and examples
373
+
374
+ ## Support
375
+
376
+ - 📖 [Documentation](docs/design.md)
377
+ - 🐛 [Issue Tracker](https://github.com/YasserShkeir/django-smart-ratelimit/issues)
378
+ - 💬 [Discussions](https://github.com/YasserShkeir/django-smart-ratelimit/discussions)
379
+
380
+ ## 💖 Support the Project
381
+
382
+ If this library has saved you time and effort, consider supporting its development:
383
+
384
+ ### Cryptocurrency Donations
385
+
386
+ - **USDT (Ethereum)**: `0x202943b3a6CC168F92871d9e295537E6cbc53Ff4`
387
+
388
+ ### Alternative Support Methods
389
+
390
+ - ⭐ **Star this repository** on GitHub
391
+ - 🐛 **Report bugs** and suggest features
392
+ - 🔀 **Contribute** code improvements
393
+ - 📢 **Share** with your team and community
394
+
395
+ Your support helps maintain and improve this open-source project! 🙏
396
+
397
+ ## Acknowledgments
398
+
399
+ - Created by Yasser Shkeir
400
+ - Inspired by existing Django rate limiting libraries
401
+ - Thanks to the Django and Redis communities
402
+ - Special thanks to all contributors