dflango
Django-like utilities for Flask applications. This package provides useful tools and patterns inspired by Django to make Flask development more productive.
Features
- ModelSchema: Marshmallow schemas with integrated SQLAlchemy model validation
- Custom Fields: Extended Marshmallow fields for common data types
- Base Views: Generic class-based views for list and detail operations
- StatisticView: Generic class-based view for dashboard KPIs and statistics
- Authentication Services: JWT-based authentication utilities
- Management Commands: Flask CLI commands for common tasks like loading fixtures
- Route Registry: Centralized route management for better organization
- Template Generation: Helpers for generating template application structures and files
Installation
From PyPI (when published)
pip install dflango
From TestPyPI (for testing)
To test the latest version from TestPyPI:
pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ dflango
Note: The --extra-index-url flag is required to install dependencies from the main PyPI repository, as TestPyPI doesn't host all packages.
From source
git clone https://github.com/Hybris-Software/dflango.git
cd dflango
pip install -e .
For development
pip install -e ".[dev]"
Quick Start
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from dflango import DFlango
# Create Flask app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
# Initialize SQLAlchemy
db = SQLAlchemy(app)
# Initialize DFlango
dflango = DFlango()
dflango.init_app(app, db)
# Or in one step:
# dflango = DFlango(app, db)
Using ModelSchema
from dflango import ModelSchema
from marshmallow import fields
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
class UserSchema(ModelSchema):
class Meta:
model = User
username = fields.Str(required=True)
email = fields.Email(required=True)
# Validate and save
schema = UserSchema()
schema.validate(request.json)
user = schema.save()
Using Class-Based Views
from dflango.views import DetailView, ListView
class UserDetailView(DetailView):
model = User
schema_class = UserSchema
class UserListView(ListView):
model = User
schema_class = UserSchema
# Register routes
app.add_url_rule('/users/<int:pk>', view_func=UserDetailView.as_view('user_detail'))
app.add_url_rule('/users', view_func=UserListView.as_view('user_list'))
Using StatisticView
StatisticView can be used to expose dashboard KPIs and generic statistics.
from dflango.views import StatisticView
from app.models import User
from app.schemas import UserReadSchema
class UserStatisticView(StatisticView):
model = User
query = User.query
read_schema = UserReadSchema
kpis = [
{
"key": "total_users",
"type": "count",
"label": "Total users",
},
{
"key": "latest_users",
"type": "last_records",
"field": "created_at",
"limit": 5,
},
{
"key": "users_by_role",
"type": "group_count",
"field": "role",
},
]
Example route:
app.add_url_rule(
"/users/statistics",
view_func=UserStatisticView.as_view("user_statistics"),
)
URL Routing with Route Registry
You can organize your routes using the RouteRegistry class like in the example below:
# Flask
from flask import Blueprint
# dFlango
from dflango.routes import RouteRegistry
# Views
from .views.users import UserListView
# Create route registry
class UsersRoutes(RouteRegistry):
blueprint = Blueprint('users', __name__)
routes = [
('/users', UserListView, 'user_list'),
]
Using Management Commands
You can launch management commands via Flask CLI. For example:
flask load-fixtures path/to/fixtures.json
flask start-app myapp
Configuration
You can configure dflango in three ways:
1. Through Flask Config Class (Recommended)
class Config:
# Flask settings
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
SECRET_KEY = 'your-secret-key'
# DFlango settings (prefix with DFLANGO_)
DFLANGO_DEFAULT_PAGE_SIZE = 50
DFLANGO_MAX_PAGE_SIZE = 200
DFLANGO_ENABLE_SOFT_DELETE = True
DFLANGO_JWT_SECRET_KEY = 'your-jwt-secret'
DFLANGO_JWT_EXPIRATION_DELTA = 7200 # 2 hours
app.config.from_object(Config)
dflango = DFlango(app, db)
2. Direct app.config update
app.config.update(
DFLANGO_DEFAULT_PAGE_SIZE=20,
DFLANGO_MAX_PAGE_SIZE=100,
DFLANGO_ENABLE_SOFT_DELETE=True,
)
dflango = DFlango(app, db)
3. Programmatically after initialization
dflango = DFlango(app, db)
# Update specific settings
dflango.update_config(DEFAULT_PAGE_SIZE=30, ENABLE_SOFT_DELETE=False)
# Or reload from app.config
app.config['DFLANGO_DEFAULT_PAGE_SIZE'] = 40
dflango.reload_config()
Available Configuration Options
| Config Key | Default | Description |
|---|---|---|
DFLANGO_JWT_SECRET_KEY |
None |
Secret key for JWT encoding/decoding |
DFLANGO_JWT_ALGORITHM |
'HS256' |
JWT algorithm |
DFLANGO_JWT_EXPIRATION_DELTA |
3600 |
JWT expiration in seconds |
DFLANGO_DEFAULT_PAGE_SIZE |
20 |
Default items per page |
DFLANGO_MAX_PAGE_SIZE |
100 |
Maximum items per page |
DFLANGO_ENABLE_SOFT_DELETE |
True |
Enable soft delete functionality |
DFLANGO_SOFT_DELETE_FIELD |
'deleted_at' |
Field name for soft delete timestamp |
DFLANGO_ENABLE_QUERY_LOGGING |
False |
Enable query logging |
DFLANGO_STRICT_VALIDATION |
True |
Enable strict validation |
DFLANGO_FIXTURES_PATH |
'fixtures' |
Path to fixtures directory |
DFLANGO_CORS_ORIGINS |
'*' |
CORS allowed origins |
DFLANGO_CORS_ALLOW_HEADERS |
'*' |
CORS allowed headers |
DFLANGO_CORS_SUPPORTS_CREDENTIALS |
False |
CORS support credentials |
Requirements
- Python >= 3.8
- Flask >= 2.0.0
- Flask-SQLAlchemy >= 3.0.0
- Flask-Migrate >= 4.0.0
- Flask-Cors >= 5.0.0
- Marshmallow >= 3.0.0
- SQLAlchemy >= 1.4.0
- PyJWT >= 2.0.0
Development
To contribute to dflango:
- Clone the repository
- Create a virtual environment:
python -m venv venv - Activate it:
source venv/bin/activate(Linux/Mac) orvenv\Scripts\activate(Windows) - Install in development mode:
pip install -e ".[dev]" - Install pre-commit hooks:
pre-commit install
Code Formatting
The project uses black, isort, and flake8 for code formatting and style.
Format code automatically:
# Using the script
./format.sh
# Or manually
black dflango/
isort dflango/
Check formatting (what CI does):
black --check dflango/
isort --check-only dflango/
flake8 dflango/
Pre-commit hooks (automatic formatting before commit):
# Install once
pre-commit install
# Run manually on all files
pre-commit run --all-files
The CI pipeline will verify (not fix) that code is properly formatted. If it fails, run ./format.sh locally and commit the changes.
Running Tests
pytest
License
This project is licensed under the MIT License - see the LICENSE file for details.
Building and Publishing to PyPI
Automatic Release with GitHub CI/CD (Recommended)
The project uses GitHub CI/CD to automatically publish to PyPI when you create a tag.
Initial setup (one-time only):
- Create an API token on pypi.org/manage/account/token
- Add the token in GitHub: Settings → CI/CD → Variables
- Key:
PYPI_TOKEN - Value: Your PyPI token
- Key:
To release a new version:
# 1. Update version in pyproject.toml and dflango/__init__.py
# 2. Commit and push
git add .
git commit -m "Release v0.1.1"
git push
# 3. Create and push the tag
git tag v0.1.1
git push origin v0.1.1
# 4. The pipeline builds and waits for confirmation on GitHub UI
# 5. Click Play on GitHub → Actions to publish
📚 Complete guide: See RELEASE.md
Manual Publication (Optional)
If you prefer to publish manually:
Step 1: Install the necessary tools
python -m pip install --upgrade build twine
Step 2: Clean and build
rm -rf dist/ build/ *.egg-info
python -m build
Step 3: Verify and publish
twine check dist/*
twine upload dist/*
Or use the automated script:
./publish.sh
Metadata
Release files for dflango 0.7.9
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dflango-0.7.9.tar.gz | 66.7 kB | Without provenance | Details for dflango-0.7.9.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dflango-0.7.9-py3-none-any.whl | Python 3 | none | any | Details for dflango-0.7.9-py3-none-any.whl |
Total release size: 151.3 kB
Release files / dflango-0.7.9.tar.gz
| Download URL | dflango-0.7.9.tar.gz |
|---|---|
| Size | 66.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
18603755d750bae77296c15b7ebf89cbe40f2082af24da06b9e635f775f708ff
|
|
BLAKE2b-256 checksum How to use checksums |
0fce2b60e8bc3409c49816e259a768fe9a938c1dbf18d70fd602129a061af723
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.3
|
Release files / dflango-0.7.9-py3-none-any.whl
| Download URL | dflango-0.7.9-py3-none-any.whl |
|---|---|
| Size | 84.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
01d850dc4749515811a9359cadd737fa34aff2b6e42f2e3b89004a9e0e59a8dc
|
|
BLAKE2b-256 checksum How to use checksums |
cebb1ae47640389a6460826b13e946634ef38889bc6fbe572e7c28ce80114b99
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.3
|
Security for dflango 0.7.9
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.