Files
fastapi-traffic/DEVELOPMENT.md

151 lines
3.1 KiB
Markdown

# Development Guide
Want to contribute or just poke around? Here's how to get set up.
## What you'll need
- Python 3.10 or newer
- [uv](https://github.com/astral-sh/uv) (recommended) or pip
- Docker if you want to test the Redis backend
## Getting started
### Using uv (the fast way)
```bash
git clone https://gitlab.com/zanewalker/fastapi-traffic.git
cd fastapi-traffic
# This creates a venv and installs everything
uv sync
```
That's it. uv figures out the rest.
### Using pip
```bash
git clone https://gitlab.com/zanewalker/fastapi-traffic.git
cd fastapi-traffic
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
```
### Redis for testing (optional)
If you want to run the Redis backend tests:
```bash
docker run -d -p 6379:6379 redis:alpine
```
## Running tests
I have 134 tests covering algorithms, backends, decorators, middleware, and integration scenarios.
```bash
# Run everything
uv run pytest
# Or with pip
pytest
# With coverage report
pytest --cov=fastapi_traffic
# Just one file
pytest tests/test_algorithms.py
# Match a pattern
pytest -k "token_bucket"
```
Tests run async by default via pytest-asyncio.
## Type checking
I use pyright in strict mode:
```bash
uv run pyright
# or just: pyright
```
## linting
Ruff handles both linting and formatting:
```bash
# Check for issues
uv run ruff check .
# Auto-fix
uv run ruff check . --fix
# Format
uv run ruff format .
```
## Running examples
The `examples/` folder has working examples you can run:
```bash
# Basic usage
uv run python examples/01_quickstart.py
# Redis example (needs Redis running)
REDIS_URL=redis://localhost:6379/0 uv run python examples/07_redis_distributed.py
```
Then open `http://localhost:8000` in your browser.
## Project layout
```bash
fastapi_traffic/
├── __init__.py # Public exports
├── exceptions.py # Custom exceptions
├── middleware.py # ASGI middleware
├── backends/
│ ├── base.py # Backend interface
│ ├── memory.py # In-memory (default)
│ ├── sqlite.py # SQLite
│ └── redis.py # Redis
└── core/
├── algorithms.py # Rate limiting algorithms
├── config.py # Configuration
├── decorator.py # @rate_limit decorator
└── limiter.py # RateLimiter class
```
## Adding a backend
1. Create a file in `fastapi_traffic/backends/`
2. Subclass `Backend` from `base.py`
3. Implement: `get`, `set`, `delete`, `exists`, `increment`, `clear`
4. Optionally: `ping`, `get_stats`, `close`
5. Add tests in `tests/test_backends.py`
6. Export from `__init__.py` if public
## Adding an algorithm
1. Add enum value to `Algorithm` in `core/algorithms.py`
2. Create a handler class
3. Register it in the dispatcher
4. Add tests in `tests/test_algorithms.py`
5. Document in README
## Tips
- Memory backend is great for development - no dependencies
- Use `skip_on_error=True` if you don't want backend errors blocking requests
- Check examples for real usage patterns
## Questions?
Open an issue. Happy to help.