Skip to main content

dflango

Pipeline Status PyPI version Python versions

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://git.hybrissoftware.it/hybris/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:

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:

  1. Clone the repository
  2. Create a virtual environment: python -m venv venv
  3. Activate it: source venv/bin/activate (Linux/Mac) or venv\Scripts\activate (Windows)
  4. Install in development mode: pip install -e ".[dev]"
  5. 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

The project uses GitLab CI/CD to automatically publish to PyPI when you create a tag.

Initial setup (one-time only):

  1. Create an API token on pypi.org/manage/account/token
  2. Add the token in GitLab: Settings → CI/CD → Variables
    • Key: PYPI_TOKEN
    • Value: Your PyPI token

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 GitLab UI
# 5. Click Play on GitLab → Pipelines 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.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dflango 0.7.2
File Size Uploaded Provenance Actions
dflango-0.7.2.tar.gz 65.7 kB Without provenance Details for dflango-0.7.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dflango 0.7.2
File Interpreter ABI Platform Actions
dflango-0.7.2-py3-none-any.whl Python 3 none any Details for dflango-0.7.2-py3-none-any.whl

Total release size: 148.5 kB

Release files / dflango-0.7.2.tar.gz

Download URL dflango-0.7.2.tar.gz
Size 65.7 kB
Tags Source
SHA-256 checksum
How to use checksums
1f8b3687721d7b1a9d3c5692bc54106b76f30ce4059cfb3fbb68c60cd4aa4fca
BLAKE2b-256 checksum
How to use checksums
855ae4b166f85fc24d8eaf46ec9b982f6b9a55af4470459d17f1a27ef150a8b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / dflango-0.7.2-py3-none-any.whl

Download URL dflango-0.7.2-py3-none-any.whl
Size 82.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
982388a9a0fa9b917eaa0caca065c4898fdda0e23aca8b63ef6239abb1aec32d
BLAKE2b-256 checksum
How to use checksums
85884ff0a668eea801d0666190b84a59fe6ec8130d8e3e36d3eeb4ef4f61b42a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for dflango 0.7.2

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.

Release history Release notifications | RSS feed

This release

0.7.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page