Skip to main content

scrud-django

A Django application for SCRUD REST services. Semantic REST API generation.

Requires Python 3.11+ and Django 5.2. Supported databases: SQLite, PostgreSQL, MySQL 8.4+ and MariaDB 11.4+ (see Databases).

Installation

uv add scrud-django
# or: pip install scrud-django

django-ninja is part of the base install, and scrud_django.urls serves the API through it. Projects that serve the API through Django REST Framework install the drf extra (see Staying on DRF):

uv add "scrud-django[drf]"

(The ninja extra of 0.16 stays as an empty alias, so existing requirement files keep working.)

For haystack search support, install the search extra:

uv add "scrud-django[search]"

Server-rendered UI

The optional scrud_django.ui app (pip install "scrud-django[ui]") serves a text/html page for every resource type at the site's own URLs (/todo-lists/7/; /api/ stays JSON only), rendered on the server through templates and stylesheets stored as resources, layered per RBAC context and shown exactly as the viewer is authorized, with htmx for editing. Include it last in the root URLconf: path("", include("scrud_django.ui.urls")). See the UI documentation and Migrating to 0.17.0.

The API (django-ninja)

scrud-django serves its resource types through django-ninja, answering as its DRF routes do (the same statuses, headers and bodies; tests/test_front_end_parity.py replays the same exchanges against both). include("scrud_django.urls") mounts scrud_django.ninja.api(types=[]), in the URL namespace scrud, and scoped-rbac's semantic documents at semantic/ (see Configuration). To serve types of your own, build the API with them and include it instead of scrud_django.urls:

# urls.py
from django.urls import include, path

from scrud_django import registration
from scrud_django.ninja import api

scrud_api = api(
    types=[
        registration.json_resource_type_spec(
            # the IRI and slug, then the arguments of
            # registration.json_resource_type but viewset_class and
            # indexing_policy_resource, as keywords
        ),
    ],
)

urlpatterns = [
    path("api/", scrud_api.urls),  # in place of include("scrud_django.urls")
    path("api/semantic/", include("scoped_rbac.semantic_urls")),
]
  • The factory is scrud_django.ninja.api(*, types=(), urls_namespace="scrud", ui_types=True, **ninja_kwargs). types are TypeSpecs, from registration.json_resource_type_spec(...) and registration.computed_resource_type_spec(...); it serves them and always the built-in types (json-schema/, json-ld/, indexing-policies/, workflow-policies/: every type's Links name its schema and context resources there), with the service catalog (services/), scoped-rbac's role routes and the collection documents. With ui_types (the default) it also serves the UI app's types when scrud_django.ui is installed (ui-components/, ui-stylesheets/, ui-css/, ui-js/, ui-branches/, ui-branch-versions/, ui-pushes/, with their write and read behaviour) and the studio's computed types when scrud_django.ui.studio is too (ui-branch-items/, ui-branch-status/, ui-type-catalog/, ui-selectable-branches/, ui-push-previews/), as scrud_django.drf.urls serves them on DRF; ui_types=False leaves them out (one API of several serves them). A type of yours cannot take one of their slugs. json_resource_type_spec(..., options=TypeOptions(...)) gives a spec the hooks the keyword arguments do not (scrud_django.core.types.TypeOptions: write and read behaviour, the methods it serves), merged with checks, object_checks and content_filter.

  • It serves no interactive docs and no OpenAPI document unless you pass docs_url= and openapi_url= (they go to NinjaAPI, as the rest of ninja_kwargs do); those routes are public. Each operation has an operationId of its own (<slug>_list, <slug>_retrieve, ...), so ninja logs no duplicate warning; one serving GET and HEAD is listed under both methods with that one id (see ninja-openapi-head-operation-id in the follow-ups).

  • Do not pass auth=: api() raises TypeError. scrud resolves the user of every request itself, so an anonymous request gets the anonymous user's grants and a hidden item is a 404.

  • Authentication is scoped-rbac's resolve_user: the SCOPED_RBAC["NINJA_USER"] hook's user, else request.auth (set only on a router you add with its own auth=, as api() takes none), else the session's. DRF's DEFAULT_AUTHENTICATION_CLASSES are not read, so a Basic or token client of a DRF project is the anonymous user on ninja (a credential nothing maps is not refused) until a hook maps it. A hook returns the user, None for the anonymous user, or raises ninja's AuthenticationError to refuse the credentials (401). For Basic credentials:

    import base64
    import binascii
    
    from django.contrib.auth import authenticate
    from ninja.errors import AuthenticationError
    
    
    def basic_user(request):
        header = request.headers.get("Authorization", "")
        scheme, _, credentials = header.partition(" ")
        if scheme.lower() != "basic":
            return getattr(request, "user", None)
        try:
            username, _, password = base64.b64decode(credentials).decode().partition(":")
        except (binascii.Error, UnicodeDecodeError):
            raise AuthenticationError() from None
        user = authenticate(request, username=username, password=password)
        if user is None:
            raise AuthenticationError() from None
        return user
    
    SCOPED_RBAC = {..., "NINJA_USER": "myapp.auth.basic_user"}
    

    A hook replaces the session lookup; it does not add to it. With a hook set, only its result is the user, so a request without Basic credentials must get the session's user from the hook itself (the example returns request.user), or a logged-in session user becomes anonymous. A hook's user who is also the request's session user is CSRF-checked on an unsafe request, whether or not Basic credentials came with the cookie. A Basic-only client has no session cookie, so a write needs no token (the same caveat as below applies). When the session belongs to user A and the Basic credentials to user B, the hook gives B and no CSRF check applies (B is not the session's user). The hook's Basic user is not CSRF-checked, exactly as DRF's BasicAuthentication (also CSRF-exempt) is not: a browser re-sends cached HTTP Basic credentials on a cross-site request, so Basic credentials suit non-browser API clients, not browsers. Send Basic credentials only over TLS. See ninja-drf-authenticators in the follow-ups.

    To keep a DRF project's clients as they are, use scrud's own hook instead, which runs DRF's authentication classes on the ninja request (DRF installed):

    SCOPED_RBAC = {..., "NINJA_USER": "scrud_django.drf.auth.drf_user"}
    

    It runs REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"], or the classes (or dotted paths) of the SCRUD_DRF_AUTHENTICATION setting when it is set, and the first that authenticates the request gives the user (none: the anonymous user). Each client is then the user it is on the DRF routes and is refused alike: credentials an authenticator refuses are the 401 DRF answers (uniform errors on or off), any other error an authenticator raises (a Throttled, say) is answered as DRF answers it, a 401 carries the first authenticator's challenge as WWW-Authenticate as on DRF (Basic realm="api" when Basic authentication comes first; none when the session's does, DRF's default), a session user's write without a valid CSRF token is a 403 (CSRF Failed: ...) as with DRF's SessionAuthentication, and Basic and token clients need no CSRF token (tests/test_ninja_auth.py compares each with the DRF route). One difference, stricter and safe: when Basic or token authentication comes before the session's and a browser sends the session user's own Basic or token credentials together with that user's session cookie, DRF takes the write as Basic or token (no CSRF check) while ninja's resolve_user CSRF-checks the session's user however it was found: a write without a CSRF token is a 403 on ninja, a 200 on DRF.

  • A computed type's compute(request, key) receives a plain Django HttpRequest on ninja (a DRF Request on DRF): read request.GET and request.user, not request.query_params or request.data, and do not hand it to a DRF permission's has_permission(request, view). Raise Http404 or PermissionDenied (Django's), as the DRF section says: a compute that raises DRF's own APIExceptions (NotFound, ValidationError, ...) is answered 404 or 400 on DRF but is a 500 on ninja.

  • TypeSpec refuses, when it is built or derived with dataclasses.replace (ImproperlyConfigured): an empty or non-string slug or IRI; a computed type that carries any hook but compute (checks, object_checks and content_filter would never be asked); a plain spec that reuses a built-in type's IRI or slug (use built_in_type_specs()); and a built-in type with hooks of its own. json_resource_type_spec refuses a schema_func, context_func or indexing_policy_func that is not callable, and computed_resource_type_spec a compute that is not (both TypeError); and register_urls() of a ResourceTypeRegistration(build_urls=False) is a TypeError. api() also refuses a slug that is not one URL segment (letters, digits, hyphens and underscores; DRF still accepts, for example, a dotted one), a reserved slug, and a slug or IRI two types share, before it registers anything.

  • A router you add to the API (scrud_api.add_router(...)) gets no authentication and no CSRF check from scrud: ninja's views are CSRF-exempt, and scrud resolves the user only on its own routes. Give it its own auth=, or scrud's entry checks (the user resolved as on scrud's routes, a session user's unsafe request CSRF-checked; a PUT, PATCH, DELETE, and a POST carrying If-Match, If-None-Match or If-Unmodified-Since, in one transaction on scrud's write database, rolled back on a status of 400 or more; a plain POST is in none of the entry's):

    from ninja import Router
    from scrud_django.ninja.entry import entry
    
    reports = Router()
    reports.add_decorator(entry, mode="view")
    scrud_api.add_router("reports/", reports)
    
  • Two APIs in one process need distinct urls_namespaces. Links (href, Location, Link headers, services/) are reversed within the namespace the request was resolved under, and the UI finds a type's routes by it. Django reverses a namespace's names within its first include only, so an API of your own in the default namespace scrud beside include("scrud_django.urls") (also scrud) fails: every scrudful route of the one included second answers 500 (its HTTP Schema Resource route cannot be reversed), and links in the namespace point at the first. manage.py check reports a scrud API's namespace included more than once (scrud_django.E010). Include your api() in place of scrud_django.urls, or give it another urls_namespace.

  • A URLconf of your own api() must also include("scoped_rbac.semantic_urls") once, as scrud_django.urls does: the role routes' (roles/, role-assignments/, user-rbac-policy/) semantic Links reverse those global names, and answer 500 without it.

  • services/ lists the types the serving API routes. A type registered in the process that it does not route (another API's, or a UI type on an api(ui_types=False)) is left out, on both front ends.

  • Content negotiation is DRF's with DRF's default renderers (JSONRenderer, BrowsableAPIRenderer): an Accept none of a route's renderers serves (Accept: application/xml) is DRF's 406 (not_acceptable), and a ?format= none of them has its 404, on both front ends. ninja does not read REST_FRAMEWORK["DEFAULT_RENDERER_CLASSES"]: a project that changes it gets DRF's answer from its DRF routes only (follow-up ninja-renderer-settings). The document routes choose their media type as DRF does, and JSON is indented as DRF indents it for Accept: application/json; indent=4.

  • The ui-css-files and ui-js-files views are the UI app's, at its base, whichever front end serves the API. A ninja route never answers text/html: a request that DRF would answer as HTML (Accept: text/html, ?format=api) gets the JSON answer.

  • A studio computed type's answer links to the API serving the request, so its ETag (the hash of that content) is that API's own: with both front ends mounted, the two answers differ only in those links and their ETag.

Staying on DRF

The Django REST Framework front end is the drf extra, in the scrud_django.drf package, and answers as it did before 0.17.0, apart from the UI app's move off /api/ (see Migrating to 0.17.0: the UI app):

uv add "scrud-django[drf]"

Add rest_framework to INSTALLED_APPS, set scrud's exception handler, and include scrud_django.drf.urls where the ninja API's scrud_django.urls would go, with scrudful's HTTP Schema Resource route once in the root URLconf (see Configuration):

# settings.py
REST_FRAMEWORK = {
    ...,
    "EXCEPTION_HANDLER": "scrud_django.drf.exceptions.scrud_exception_handler",
}
# urls.py (the root URLconf)
from scrudful.rest_framework import hsr_urls

urlpatterns = [
    path("api/", include("scrud_django.drf.urls")),
    path("", include(hsr_urls())),
]

scrud_django.drf.urls includes scoped-rbac's DRF role routes and its semantic documents (semantic/). Register types of your own on it with registration.json_resource_type (see Registering resource types); the views, serializers, filters and permissions are in scrud_django.drf (see Migrating to 0.17.0: the DRF adapter). DRF's authentication classes authenticate these routes as before; to keep the same clients on a ninja API, use the scrud_django.drf.auth.drf_user hook (see The API (django-ninja)).

Your own models with workflow (ninja)

An app's own Django models (not scrud resources) can be served through ninja with scrud's workflow: its policies, its scrud_post_save and scrud_post_delete signals and its SCRUD_WORKFLOW_ACTIONS. A model needs no scrud base class. You write the router from scoped-rbac's public ninja blocks and add scrud_django.ninja.workflow_check, which returns a ModelWorkflow:

workflow_check(iri, *, model, schema_out=None, state_of=None, contexts_for=None)
  • iri is the model's type IRI, the resource_type of its policies.
  • Pass exactly one of schema_out (the state a policy's conditions read is the JSON the API answers with, schema_out's model_dump(mode="json")) or state_of (a function of the instance returning a mapping); anything else is a TypeError. The default state reads an unsaved instance on a create, so schema_out's fields the database fills in must be optional (id: int | None = None), else a create is a TypeError that says so; or pass state_of=.
  • contexts_for is the instance's contexts, by default scoped-rbac's object_contexts (rbac_contexts, else rbac_context). Pass the same function to scoped-rbac's blocks.
  • Call it once per model, where the router is built. It also governs the model (below).

The router below is the one tests/own_models.py runs (the test suite checks that the README shows it):

from django.http import HttpResponse
from ninja import Schema
from scoped_rbac import access
from scoped_rbac.ninja import (
    authorize_write,
    checked_list,
    default_contexts_from,
    detail_iri,
    item_check,
    list_check,
    rbac_load,
    request_json,
    resolve_user,
    validate_body,
)
from scrudful.ninja import ScrudfulRouter, scrudful, scrudful_create, scrudful_list

from scrud_django.ninja import workflow_check

from .models import Article


class ArticleIn(Schema):
    title: str = ""
    state: str = "draft"
    rbac_context: str = ""


class ArticleOut(Schema):
    # Optional: the workflow reads ArticleOut's JSON of a create's unsaved
    # instance too, which has no primary key yet.
    id: int | None = None
    title: str
    state: str
    rbac_context: str


ARTICLE = "myapp://Article"

# Its workflow reads the JSON the API answers with (ArticleOut's).
ARTICLE_WORKFLOW = workflow_check(ARTICLE, model=Article, schema_out=ArticleOut)

DETAIL = "article-detail"
QUERYSET = Article.objects.all()


def href(request, obj):
    return detail_iri(request, DETAIL, obj.pk)


def rows():
    return QUERYSET.order_by("pk")


# The request and object checks run inside ARTICLE_WORKFLOW.covering: a grant
# conditioned on scrud_workflow allows a POST to the list and a PUT to an item
# (the workflow check then decides the transition), and refuses anything
# else, as on scrud's resource routes. A list's GET is never covered.
load = ARTICLE_WORKFLOW.covered(
    rbac_load(Article, ARTICLE, queryset=QUERYSET, post_save_checked=True),
    item=True,
)
before = item_check(ARTICLE, load=load)["before"]
create_check = {"before": ARTICLE_WORKFLOW.covered(before, item=False)}
item_hooks = {"load": load, "before": ARTICLE_WORKFLOW.covered(before, item=True)}
listing = list_check(ARTICLE, lambda request, **path_params: rows())


def updater(obj, values):
    """The save of an update: `values` set on `obj` (the row as
    ``save_checked`` locked it), then saved."""

    def save():
        for name, value in values.items():
            setattr(obj, name, value)
        obj.save()
        return obj

    return save


router = ScrudfulRouter()


@router.api_operation(
    ["GET", "HEAD"],
    "/",
    response=list[ArticleOut],
    url_name="article-list",
    operation_id="article_list",
)
@scrudful_list(href_func=href, page_size=100, max_page_size=1000, **listing)
def list_articles(request):
    return checked_list(request)


@router.post(
    "/",
    response={201: ArticleOut},
    url_name="article-list",
    operation_id="article_create",
)
@scrudful_create(location_func=href, **create_check)
def create_article(request):
    resolve_user(request)
    content = request_json(request)
    contexts = access.call_contexts_from(
        default_contexts_from,
        access.contexts_body(content),
        where=f"create of {ARTICLE}",
    )
    with ARTICLE_WORKFLOW.covering(request, item=False):
        authorize_write(request, ARTICLE, contexts, access.body_mapping(content))
    values = validate_body(request, ArticleIn, content)
    return ARTICLE_WORKFLOW.save_checked(
        request,
        instance=None,
        values=values,
        save=lambda: Article.objects.create(**values),
        queryset=QUERYSET,
    )


@router.api_operation(
    ["GET", "HEAD"],
    "/{pk}/",
    response=ArticleOut,
    url_name=DETAIL,
    operation_id="article_retrieve",
)
@scrudful(**item_hooks)
def retrieve_article(request, pk: str, obj):
    return obj


@router.put(
    "/{pk}/", response=ArticleOut, url_name=DETAIL, operation_id="article_replace"
)
@scrudful(**item_hooks)
def replace_article(request, pk: str, obj):
    values = validate_body(request, ArticleIn, request_json(request))
    return ARTICLE_WORKFLOW.save_checked(
        request,
        instance=obj,
        values=values,
        save=updater(obj, values),
        queryset=QUERYSET,
    )


@router.delete(
    "/{pk}/", response={204: None}, url_name=DETAIL, operation_id="article_destroy"
)
@scrudful(**item_hooks)
def destroy_article(request, pk: str, obj):
    ARTICLE_WORKFLOW.delete_checked(request, instance=obj)
    # No content, so no Content-Type (ninja's would be application/json).
    response = HttpResponse(status=204)
    del response["Content-Type"]
    return response
  • save_checked runs the whole write in one transaction: for an update it locks the stored row (select_for_update) and copies the row's stored fields onto instance, then runs the workflow check against the stored and the proposed state, scoped-rbac's save_checked under authorizing_write, and your save. So a router must pass every change through values and save: a field set on the instance beforehand is overwritten. The transaction commits, and scrud_post_save and the SCRUD_WORKFLOW_ACTIONS for the IRI run on commit, with sender the model class, instance, resource_type_uri the IRI, using the write's database, and transitions, transition_data and transition_error computed from state_of, as for a resource (an instance in no context, contexts_for giving none, is checked and reported under the settings default, in context None). save must return the one instance it saved (a TypeError otherwise). If it wrote something other than the checked values (a Model.save override, say), each context where the saved state is invalid is logged as a warning on the scrud_django.workflow logger. delete_checked locks the row the same way (a 404 when another request deleted it meanwhile, and no signal) and sends scrud_post_delete on commit.
  • Per-transition grants (conditioned on scrud_workflow) work because the router wraps its request and object checks with covering and covered, which run them inside authorizing_write: a grant conditioned on scrud_workflow then allows a POST to the list and a PUT to an item, and the workflow check decides the transition, as on scrud's resource routes. Without the wrapper such a grant allows nothing. A covered check is allowed on the promise that the workflow check follows: wrap only the checks of a POST to the list or a PUT to an item whose write goes through ModelWorkflow.save_checked. A covered route that saves any other way lets those grants write unchecked.
  • The policies for a model are WorkflowPolicy resources whose resource_type is the model's IRI, or SCRUD_WORKFLOW["DEFAULT_WORKFLOW_POLICIES"], as for a scrud type (see Workflow policies). The system checks E002, E003, E005 and W001 cover them, and W006 accepts a governed model's IRI.
  • A save of a governed model outside save_checked (the admin, the shell, a management command, an endpoint that forgot the check) is not refused: each context where it is invalid is logged as a warning on the scrud_django.workflow logger, as for a resource. Whether such saves should be refused is open (scrud-django's GitLab issue #56, https://gitlab.com/dcharbon/scrud-django/-/issues/56). Server code that has done the check itself wraps its saves in scrud_django.core.transitions.checked_save(Model). As for a resource, QuerySet.update(), bulk_create() and bulk_update() send no signals and are not logged. The model's state_of and contexts_for run on every such save too: one that raises fails it (in the admin, say).
  • Deletes are not checked against the workflow, only authorized (follow-up delete-no-workflow-check).
  • The router is written by hand because scoped-rbac 0.12.1's crud_router takes no extra checks (follow-up scoped-rbac-crud-router-checks). It leaves out what crud_router does beyond these blocks: its OPTIONS allowed hook (the private _allowed_as_drf; scrudful decides Allow from each method's before and load instead), its running a conditional create in one transaction (the private _conditional_create_atomic; the example's model has no validators, so a create takes no precondition), the detail-route mark (DETAIL_MARK, not exported), the PATCH route, and the schema and context links (scoped_rbac.semantic, which needs a type IRI without /). The router's own checks run before the write transaction, on the row as loaded (follow-up own-model-router-checks-before-transaction).

The demo's articles app (demo/articles/) is a working copy: a model whose policy has a draft and a published state.

Configuration

Required

Add django.contrib.auth, django.contrib.contenttypes, reversion, scoped_rbac and scrud_django to INSTALLED_APPS (and rest_framework on DRF, see Staying on DRF):

INSTALLED_APPS = [
  ...
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'reversion',
  'scoped_rbac',
  'scrud_django',
  ...
]

Include the scrud-django URLs, the ninja API (scrud_django.ninja.api, in the URL namespace scrud). They include scoped-rbac's semantic URLs (semantic/), which serve the schemas and JSON-LD contexts of scoped-rbac's own Role, RoleAssignment and Policy resources (the role endpoints' Link headers point there); a scrud resource type's schema and context are its json-schema/<id>/ and json-ld/<id>/ resources:

urlpatterns = [
    path("api/", include("scrud_django.urls")),
]

On DRF, include scrud_django.drf.urls instead (it includes the semantic URLs too). If you mount URLs yourself (your own api()), include scoped_rbac.semantic_urls once, for example path("semantic/", include("scoped_rbac.semantic_urls")).

Set the base URL the API is served at, and, on DRF, include scrudful's HTTP Schema Resource route once, in the root URLconf (the ninja API serves its routes' HTTP Schema Resources itself). An OPTIONS is a 204 without content whose Link names the path's HTTP Schema Resource (HSR), a JSON document describing its methods that a GET serves; scrudful builds it without a request, so its links, and the HSR link each response carries, resolve against SCRUDFUL["BASE_URL"] (scrudful resolves only relative links against it; scrud's other response Links are absolute URLs built from the request). Allow lists the methods the requester's grants allow there. A list's POST is checked without a body, so it is listed when they may write in some context, whatever conditions their grants put on the body. A detail route's methods are checked against the stored resource, which the OPTIONS loads as the first method the requester may use somewhere loads it: a resource that is missing, or that method may not reach, is a 404; a requester who may use no method there gets 204 with Allow: OPTIONS whether or not it exists.

# urls.py (the root URLconf), on DRF
from scrudful.rest_framework import hsr_urls

urlpatterns = [
    path("api/", include("scrud_django.drf.urls")),
    path("", include(hsr_urls())),
]
# settings.py
SCRUDFUL = {"BASE_URL": "https://api.example.com"}

On DRF, without the include, every request of a scrud view raises ImproperlyConfigured (and manage.py check reports scrudful.E003). On ninja, without SCRUDFUL["BASE_URL"], the HTTP Schema Resources whose links are relative (those of each type's routes and of the role routes) fail (500, ninja's ConfigError), and manage.py check warns (scrud_django.W009).

Databases

scrud-django supports SQLite, PostgreSQL, MySQL 8.4+ and MariaDB 11.4+. CI runs the suite on SQLite, PostgreSQL 14, MySQL 8.4 and MariaDB 11.4.

Run the database at READ COMMITTED, the supported transaction isolation level (PostgreSQL's default; Django's MySQL backend, which MariaDB uses too, sets it unless OPTIONS["isolation_level"] says otherwise). manage.py check --database <alias>, with the alias your router gives for Resource writes (and migrate of it), warns about another (scrud_django.W002). The database checks (W003-W006, and E002, E003, E005 and W001 for stored workflow policies) report nothing on a database whose scrud_django migrations are not all applied, so that migrate can run, nor on one where your routers' allow_migrate keeps scrud_django's tables out (an analytics database); one that fails reading a migrated database (a missing grant, a schema out of step with the migrations) warns scrud_django.W007, naming the check and the error, rather than passing. A file SQLite database that takes concurrent writes needs "OPTIONS": {"transaction_mode": "IMMEDIATE"}: otherwise a second concurrent writer fails with "database is locked" instead of waiting.

MySQL and MariaDB:

  • Use Django's MySQL backend with mysqlclient, InnoDB tables (the default), and a utf8mb4 database (MariaDB stores a resource's JSON content as text in the database's character set) and connection (Django's default OPTIONS["charset"]).
  • Contexts are matched exactly, code point for code point, whatever the database's collation: the ResourceContext and ResourceRemoval contexts are stored as their UTF-8 bytes (VARBINARY(2048)), so "acme", "ACME", "acmé" and "acme " are four contexts, as on the detail route.
  • On MariaDB a request body may be nested at most 31 levels deep (it is 100 elsewhere): MariaDB's JSON column refuses a deeper document.

Registering resource types

Both front ends serve the built-in types (JSON Schemas, JSON-LD contexts, indexing and workflow policies). On ninja, a type of your own is a registration.json_resource_type_spec(...) (the same arguments as below, but viewset_class and indexing_policy_resource) passed to your own scrud_django.ninja.api(types=[...]), which takes the place of scrud_django.urls (see The API (django-ninja)). On DRF (scrud_django.drf.urls, the drf extra), register each type of your own with registration.json_resource_type, which stores the type, its JSON Schema and its JSON-LD context (as resources) and returns the URLs of its list (<slug>/: GET, HEAD, POST) and detail (<slug>/<pk>/: GET, HEAD, PUT, DELETE) routes, named <slug>-list and <slug>-detail:

from django.urls import include, path
from scrud_django import registration

NOTE = "https://example.com/json-ld/Note"

urlpatterns = [
    path("api/", include("scrud_django.drf.urls")),
    path(
        "api/",
        include(
            registration.resource_types(
                registration.json_resource_type(
                    resource_type_uri=NOTE,
                    slug="notes",
                    schema_func=lambda: {
                        "type": "object",
                        "properties": {"text": {"type": "string"}},
                        "required": ["text"],
                    },
                    context_func=lambda: {
                        "@context": {"text": "https://schema.org/text"}
                    },
                ),
            )
        ),
    ),
]

schema_func and context_func return the document (a dict, or its JSON text, for example read from a file of your package, as the demo's demo/demo/urls.py does). A POST or PUT body is validated against the schema, whose $refs may only point inside it (#/...). The registration runs when the URLconf is imported. When the database fails then, it still returns the routes and logs the failure (logger scrud_django.registration): a warning while the database is unreachable, not migrated (before the first migrate, which is expected), or its migration state cannot be read (a database error); an error when it is reachable and migrated (a missing grant, a schema out of step with the migrations), which needs fixing, or when its migration state cannot be told for another reason (a broken migration graph, logged with its traceback). Whether it is migrated is asked once for the registrations that fail together, not once each. The type is registered when a request (or code) next reads it, so the process serves it once the database is back, and until then a request for it fails (500), not 404. A process start stores nothing when the type and its documents are unchanged; under DEBUG, a type's row follows the registration's arguments (slug, revision, schema_uri, ...); outside it, the stored row keeps its slug, revision and URIs, and only its documents (and uses_reversion) are updated. Pass viewset_class=ResourceViewSetGenericFilter (scrud_django.drf.views) for a list that filters on its query parameters (?text=...; with scrud_django.ui installed, its URL parameters ui-branch, ui-branch-confirm, ui-scope, ui-mode and ui-safe are not filters).

Hooks on json_resource_type, honoured by every front end, narrow what the grants allow (they can only refuse, and refuse superusers too, as an IsAuthorized subclass does). A hook must return True to allow: any other return (None, "yes", 1) refuses.

  • checks: callables (request, resource_type, body, context) -> bool that govern writes: asked of a write in each context it writes, of the stored resource of a PUT, PATCH or DELETE in each of its contexts, of the saved resource in each of its contexts, and of a workflow transition in each context it is authorized in. Unlike an IsAuthorized subclass, whose object check allows a PUT or DELETE when any context the resource is stored in allows it, checks must allow in every one: a resource in ["a", "b"] whose check refuses "b" can be neither updated (not even moved to "a") nor deleted (403). They never hide a read, and a type with only checks lists by SQL; a type that wants both registers both.
  • object_checks: callables (request, resource_type, obj) -> bool that govern reads and objects, asked of a resource's content wherever the object is checked (the detail route of every method, each listed resource). A refused resource is hidden (404). A write of a resource they would hide is refused too (403, after the save, which is rolled back).
  • content_filter=True: the list filters on its query parameters. It is read when the routes are built, so registering a slug again replaces the other hooks but not an already built route's filter.

Hooks are keyed by the type's IRI: registering a type again replaces the hooks registered for it before (a different set logs a warning on scrud_django.core.types), and requirement_for imports ROOT_URLCONF once per process, so a worker that never served a request still has them. Slugs sharing a type IRI must register the very same hook objects, or the second gets ImproperlyConfigured: use module-level functions, since closures a factory builds in the URLconf are new objects each time it is imported, and a re-import then raises.

To move the rule of an IsAuthorized subclass's has_context_permission to hooks, register it twice. As a checks= callable it governs writes, but it no longer hides reads, and it is stricter on a resource stored in several contexts: the subclass allowed a PUT or DELETE that any of them allowed, a check must allow it in every one. To hide what the subclass refused to read, add an object_checks= callable that applies the same rule to each of the resource's contexts (rbac_contexts_of(obj), from scrud_django.mixins.resource_mixin) and combines the answers as the subclass did. scoped-rbac's has_object_permission allows when any context allows, so use any unless the subclass overrode it:

from scrud_django.mixins.resource_mixin import rbac_contexts_of


def not_archived(request, resource_type, obj, context):
    return context != "archived"


def readable_somewhere(request, resource_type, obj):
    return any(
        not_archived(request, resource_type, obj, context)
        for context in rbac_contexts_of(obj)
    )


json_resource_type(..., checks=[not_archived], object_checks=[readable_somewhere])

The UI app (scrud_django.ui) reads through the core, which asks a type's grants and hooks but never a DRF view's own permissions, so it fails closed on a type registered with a custom viewset_class (any but ResourceViewSet, ResourceViewSetGenericFilter, the document types' own and ComputedResourceViewSet, or the content_filter=True variant of one): whatever authorizes there (IsAuthorized subclasses, their &, | and ~ compositions, the viewset's own methods) is DRF's only. Its pages, embeds, prefixes and studio previews answer 404, as for a slug the UI does not serve, and the system check scrud_django_ui.W003 names it, unless the type opts in with either:

  • both checks= and object_checks=: its rules declared to the core, which then applies them on the UI as on every front end; or
  • ui_authorization="core" (on json_resource_type or computed_resource_type): a statement that the core's checks (its grants and any hooks) are already complete for it, because the viewset adds no authorization of its own. The UI then serves it by those checks alone, so declare it only when that is true.

The UI serves a type only when the views its API routes resolve to (in the URLconf serving the request) were built by registration: a type whose <slug>-list or <slug>-detail you route yourself (MyViewSet.as_view(...), or a registration's view wrapped in a decorator) is refused the same way, since nothing tells what authorizes it. The UI finds a type's routes by those names outside any URL namespace (registration's) or in the urls_namespace of a scrud ninja api() (which notes it, scrud_django.core.urls.note_api_routes; core.urls.api_route_name and api_reverse look in both), so it serves the types of a DRF, ninja or mixed project alike; a namespace an outer include nests the API in is not looked in. The system check scrud_django_ui.W004 names each registered type with no such route, and scrud_django_ui.W005 each type whose slug is one of the UI app's own route segments (ui-css-files, ui-js-files, and studio with the studio installed), whose pages those routes shadow. Such a type opts in by registering its options with scrud_django.core.types.register_type_options(type_uri, TypeOptions(ui_authorization="core"), slug=slug) (or both hooks). ninja's json_resource_type_spec takes no ui_authorization=: a type registered on both front ends records the hooks of whichever registration runs last, so without it there the DRF declaration is replaced (a warning is logged) and the UI refuses the type.

Grant roles (scoped-rbac) on the type URI for its resources (http.GET, http.POST, http.PUT, http.DELETE) and http.GET on its list type, https://api.openteams.com/json-schema/ResourceCollection?contents_type=<type URI> (scrud_django.collection_type_uri_for), in each context whose resources a user may list. A resource's context is its content's rbac_context (the default context "" without one).

A grant conditioned on the scrud_workflow operator ({"condition": {"operator": "scrud_workflow", "authorized_transitions": ["cancel"]}}) grants workflow transitions and nothing else: the transitions it lists, in a POST or PUT the workflow check covers, a scrud viewset's create (POST to the list) or update (PUT to the detail route). It never allows a GET, a list or a DELETE, even with the action "*", nor any other write, such as an @action of a viewset subclass, which the workflow check does not see, so a role that should read needs its own http.GET grant, and one that should call such an action its own grant for its method. authorized_transitions must be a list of transition names (__INITIALIZE__ for a create, __SAME_STATE__ for an update that keeps its state); anything else refuses everywhere.

A list shows what the detail route shows, as far as the view's IsAuthorized permissions (and subclasses of it) decide: an object such a subclass refuses to read is missing from the list and a 404 on its detail route, for every method (an object the user may read but not write gets 403). Another DRF BasePermission on the view, such as an owner check in has_object_permission, is not asked for lists, as in DRF: its detail route refuses a resource that its list still shows. Put such a rule in an IsAuthorized subclass (override has_object_permission or has_context_permission), or apply it in a filter backend of the view (or its get_queryset), for the list to follow it.

A POST to a list evaluates its If-Match, If-Unmodified-Since and If-None-Match (RFC 9110) against the list's ETag and Last-Modified as the requester would GET them from that URL: a failed one is a 412 and nothing is created. Computing them is a GET of the list, so where that GET is a 400 conditional_list_too_large (past SCOPED_RBAC["CONDITIONAL_LIST_MAX_ROWS"] rows evaluated one by one), so is such a POST. If-Match: * and If-None-Match: * need no validators (the list always exists): the first creates as an unconditional POST does, the second is always a 412. A POST that needs the validators evaluates them and creates in one transaction holding its type's ResourceType row, so two such POSTs with the same If-Match give one 201 and one 412.

A write is checked in the contexts the resource ends up in, every one of them, and (by the object check of a PUT or DELETE) in any one context it is stored in. Removing a resource from a context, by a PUT whose rbac_context leaves it out, needs no grant in that context unless a workflow policy applies there, as a DELETE allowed in one context deletes the resource from all of them.

An rbac_context that is a list of strings stores the resource in each of them. Any other value that is not a string (null, a number, an object, or a list holding a number, bool or null) stores it in the default context "". A list holding an array or an object is a 400 (invalid, naming rbac_context).

A grant's CEL condition that reads rbac_context reads the context it is evaluated in: the content with that context as its rbac_context. scrud's post-save check, the object checks of a detail route (and whether a refused resource is a 404 or a 403) and lists read every context so, and the workflow check every context it checks, those an update moves the resource out of included; scoped-rbac's request check of a POST or PUT reads each value of a list of strings so, and any other body as written. So rbac_context != "x" refuses a write into "x" (or into "" with an rbac_context that is not a string), and refuses a resource in "x" however it is stored. A resource stored in several contexts is readable, and may be updated or deleted, where any one of its contexts allows it: rbac_context != "x" does not hide a resource stored as ["x", "y"] from a grant that holds in "y". To keep a grant out of a context, assign it in the contexts it covers (RoleAssignment.rbac_context) instead.

Code of your own reads what it always did: an operator function, and a has_context_permission of your own, get the content as stored (or the body as sent), its rbac_context the whole value. Its super() call reads that too; to have scoped-rbac's check read each context as the object is there, pass it scrud_django.drf.permissions.condition_resource(obj, context). On a view with such an override, the scrud views also ask the grants, each context read as the resource is there, on the detail route and after a write, as its list does: the override narrows what the grants allow. A context that a contexts_for of your own names, and that is not one of the resource's, leaves the object as it is (docs/follow-ups.md, custom-contexts-conditions). A view of your own that composes scoped-rbac's AccessControlledAPIView with ResourceViewMixin puts scrud_django.drf.mixins.ReadableMixin first, as the scrud viewsets do, so that a refused write of a resource readable in one of its contexts is a 403, not a 404.

Configure Django REST Framework to authorize with scoped-rbac and to answer errors as RFC 7807 problem details while keeping scrud-django's own validation and workflow error bodies (the scrud views' other errors, precondition failures included, are problem details while scoped-rbac's SCOPED_RBAC["UNIFORM_ERRORS"] is on, its default, and DRF's native {"detail": ...} bodies when it is off):

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["scoped_rbac.permissions.IsAuthorized"],
    "EXCEPTION_HANDLER": "scrud_django.drf.exceptions.scrud_exception_handler",
    ...
}

Request bodies must be JSON: a form or multipart body gets 415, and a POST or PUT with an empty body, or without a Content-Length (chunked), 400. JSON Schema default values are not applied: a resource is validated against its type's schema, stored and checked against its workflow policy exactly as it was sent, so send every value you want stored.

If you use DATABASE_ROUTERS, route the writes of scrud_django's models (Resource, ResourceType, ResourceContext, ResourceRemoval) to one database alias: scrud-django writes a resource, its context rows and its removal stamps in one transaction there, and the scrud_django.E004 system check reports a split. Routing these models by instance hint is not supported.

Server code that writes a WorkflowPolicy resource should go through ResourceRegistration. Code that locks a policy's row itself (Resource.objects.select_for_update()) and then saves or deletes it must call scrud_django.registration.lock_if_workflow_policy in the same transaction, on every database, before the select_for_update(): the save or delete takes the WorkflowPolicy type lock, and taking it after the row's lock deadlocks with an API write of the policy, which holds the type lock and waits for the row. Read the type without locking the row:

from django.db import transaction

from scrud_django.models import Resource
from scrud_django.registration import (
    get_resource_type_for,
    lock_if_workflow_policy,
    write_db,
)

db = write_db()
with transaction.atomic(using=db):
    # Before the row lock; the type is read without it.
    lock_if_workflow_policy(get_resource_type_for("workflow-policies", using=db), db)
    policy = Resource.objects.using(db).select_for_update().get(pk=pk)
    policy.content = new_content
    policy.save()  # or policy.delete()

A plain save() or delete(), without a row lock of its own, takes the type lock before the row by itself.

Lists filter resources by their ResourceContext rows, one per context the content names, which Resource.save() (and so ResourceRegistration and the API) keeps in step. Rows written with QuerySet.update(), bulk_create() or bulk_update() go stale (and run no workflow action, see Workflow actions). manage.py scrud_sync_contexts --check lists the resources whose rows disagree with their content (exit status 1 if any), and manage.py scrud_sync_contexts re-syncs them; the scrud_django.W004 database check reports resources that have no row at all. The workflow policy of a context is found by those rows too, and also by the policy's content, so that stale rows do not hide a policy (see scrud_django.workflow.stored_policies_in for the one case they still can).

DRF's own default permission is AllowAny. The scrud-django viewsets set IsAuthorized themselves, but any other view in your project (and any view you build on scoped-rbac) relies on DEFAULT_PERMISSION_CLASSES to fail closed.

Permission checks get plain data, as scoped-rbac's own do. On a POST or PUT, your IsAuthorized subclasses (has_permission, contexts_from) and the operators of your grants' conditions get the parsed body itself (request.data); the workflow check gives their has_context_permission and operators the body as sent, with the transition it authorizes as scrud_django.drf.permissions.current_transition(); and every object check of a Resource view (the detail route's, the post-save check, a list's per-object check) gives has_object_permission, has_context_permission, contexts_for and operators the resource's content, the dict the Resource holds ({} for content that is not a JSON object). These are exact dicts and lists, so on Resource views an operator that evaluates CEL itself passes what it got. GenericViewMixin views give their object checks your model's instance, as scoped-rbac does, so an operator there that evaluates CEL itself passes the model's to_cel(): give the model one. scoped_rbac.access.cel_mapping(None, obj) reads it too, but without a request it leaves out the fields a model's cel_resource(request) gives the policy's CEL, and for a model without to_cel() it is {}. An operator written as a denial (not cel.is_true(...)) must therefore refuse when the fields it reads are missing: on {} the CEL result is undetermined, and not turns it into an allow. A check must only read what it gets (obj.get("owner"), never obj.pop("owner")): one that changes it changes what is stored (or, on a read, what the response shows), a bug in that check. Scoped-rbac's default contexts_for reads a resource's contexts from its content on the scrud views, whatever your get_permissions returns; a contexts_for of your own calls scrud_django.drf.permissions.resource_contexts(obj) where it would call super().contexts_for(obj), which cannot read a dict (a 500, failing closed).

Resource type metadata is public by design: the service list (services/), each type's collection schema (collections-json-schema/<slug>/) and collection JSON-LD context (collections-json-ld/<slug>/) answer anyone, anonymous users included. Clients need the schemas and contexts to build requests, and resource types are global, not per context. The resources themselves, a type's schema and context documents among them, are RBAC-checked on their own routes.

The Django admin shows Resource and ResourceType to superusers only: a write there bypasses scoped-rbac, the workflow and JSON Schema validation.

Computed resource types

A computed type has a schema and a JSON-LD context like any resource type, but its content is computed per request, never stored: a read-only view of data the server derives for the requesting user. Write its compute(request, key) (return a mapping; raise Http404 or PermissionDenied) and give the API its spec, registration.computed_resource_type_spec:

from scrud_django import registration
from scrud_django.ninja import api


def branch_summary(request, key):
    # Return only what request.user may read as JSON.
    return {"name": key, "items": []}


scrud_api = api(
    types=[
        registration.computed_resource_type_spec(
            resource_type_uri="http://example.org/BranchSummary",
            slug="branch-summaries",
            schema_func=lambda: SCHEMA_JSON,
            context_func=lambda: CONTEXT_JSON,
            compute=branch_summary,
        ),
    ],
)

It routes branch-summaries/<key>/ only (route name branch-summaries-detail, in the API's namespace: scrud:branch-summaries-detail; no list route, so a computed type is not in the service catalog, which gives each type's list URL) and adds no revision history. A GET answers the content with an ETag (the SHA-256 of its canonical JSON) and a 304 for a matching If-None-Match; any method other than GET, HEAD and OPTIONS is a 405. The response carries the Link headers to the type's schema and JSON-LD context, as a stored resource's does. The route requires an authenticated user and applies no authorization of its own to the content: compute must ask the same checks the stored resources' views do. The type is registered, so a published branch's prefix claims its slug, and the UI's page for it renders it through the UI cascade as view-only content. Registering a slug again replaces its compute.

On DRF (the drf extra), register it with registration.computed_resource_type instead, which takes the same arguments and returns the URL patterns to add (route name branch-summaries-detail, outside any namespace), served by scrud_django.drf.computed.ComputedResourceViewSet:

urlpatterns += registration.computed_resource_type(
    resource_type_uri="http://example.org/BranchSummary",
    slug="branch-summaries",
    schema_func=lambda: SCHEMA_JSON,
    context_func=lambda: CONTEXT_JSON,
    compute=branch_summary,
)

In place of compute=, it takes a viewset_class=: a subclass of ComputedResourceViewSet implementing compute(self, request, key). One of the two is needed; a type registered with only a DRF viewset_class has no UI page and is served on DRF alone.

Search (optional)

With the search extra, also add haystack to INSTALLED_APPS and configure a connection, for example:

HAYSTACK_CONNECTIONS = {
    "default": {
        "ENGINE": "haystack.backends.whoosh_backend.WhooshEngine",
        "PATH": BASE_DIR / "whoosh_index",
    },
}
HAYSTACK_SIGNAL_PROCESSOR = "scrud_django.search.OnCommitSignalProcessor"

OnCommitSignalProcessor updates the index when a write commits. haystack's own RealtimeSignalProcessor indexes inside the write, so a write that scrud-django then rolls back (for example with 403, when the stored resource lands in a context the writer may not write in) would stay in the index.

Workflow policies

A workflow policy (a WorkflowPolicy resource for one type in its rbac_context, else the type's SCRUD_WORKFLOW["DEFAULT_WORKFLOW_POLICIES"] entry) names its states in initial_states (where a create may put a resource) and states (the others); a state is named in one of them, not both. Each state's condition is a CEL expression over the resource's content, each top-level property a variable. Unlike a grant's condition, it reads rbac_context as stored: the whole value (a list for a resource in several contexts), the same in every context the write is checked in, not the context being checked. State conditions are compiled without type checking, so a misspelled property (stauts == "done") is accepted, never present, and its state unreachable: manage.py check --database default warns (scrud_django.W005) where a default policy's condition reads a property its type's JSON Schema does not define (rbac_context is always allowed); stored policies are not checked. It says nothing where it cannot tell: for a type not registered on that database or whose schema is not stored there, a schema without a properties object or one that may allow other properties (additionalProperties true or a schema; absent counts as false) or add some (patternProperties, allOf, anyOf, oneOf, $ref, if/then/else, dependencies, dependentSchemas, unevaluatedProperties), a default that is invalid (scrud_django.E001), or a database that is not migrated. A condition that fails to evaluate (a property the content lacks) is no match, and is logged at DEBUG on the scrud_django.workflow logger, naming the policy and the state.

A settings default is a fallback, not a floor: a stored WorkflowPolicy for a type in a context replaces the default for that type there (deleting it restores the default); it is not combined with it and need not be stricter. Writing a WorkflowPolicy is authorized by grants on the WorkflowPolicy type in its context alone, not on the type it governs. So whoever may POST a WorkflowPolicy in a context can, with no rights on the governed type, give any type there a workflow of their own, looser than the default, and rename or redefine its transitions, which changes what every scrud_workflow grant in that context allows (its authorized_transitions name transitions). Treat http.POST, http.PUT and http.DELETE on http://api.openteams.com/json-ld/WorkflowPolicy as administrative grants; no deployment-wide workflow invariant can be enforced through the defaults (docs/follow-ups.md, policy-defaults-are-fallbacks).

A policy's state conditions must be mutually exclusive: content is in the one state whose condition it meets. The order of the conditions decides nothing, since a policy stored in a JSON column does not keep it (PostgreSQL's jsonb and MySQL's JSON reorder an object's keys). Content that meets the conditions of more than one state is ambiguous: a create or update whose body is ambiguous, or an update of a resource whose stored content is, is refused (400, workflow-transition-invalid, with the states it meets in matching_states and in its message, unless the error is hidden from a writer who may not read the policy or the resource). A policy whose conditions overlap is not refused when it is written (whether two CEL conditions can both hold is not decidable in general); write each condition so that it excludes the others (status == "review" && !published, not status == "review" beside published).

Workflow actions

SCRUD_WORKFLOW_ACTIONS is a list (or tuple) of dotted paths to mappings of type URI to {"on_save": callable, "on_delete": callable}; a later mapping's entry for a type replaces an earlier one's. An action runs when the write of a resource of its type commits, never for a write that is rolled back. The scrud_post_save and scrud_post_delete signals fire inside the write; a receiver whose work leaves the database should wrap it in transaction.on_commit(..., using=using). Their using is the database the write went to (the router's db_for_write), even for an instance read from a replica.

Actions and receivers are called as action(sender, **kwargs), with the keyword arguments Django gives a receiver: signal (the signal sent), instance, using, resource_type_uri and action (CREATE, UPDATE or DELETE); scrud_post_save adds update_fields, transition_data, transition_error and transitions, and scrud_post_delete adds pk, the deleted resource's primary key (the instance is the deleted one, whose pk Django has set to None).

transition_data is a scrud_django.workflow.TransitionData (proposed_state, prior_state, transition; immutable) under the workflow policy in effect in the first context the content names that has one, or None when no policy applies or the write is invalid there; transition_error is then the workflow error, and None otherwise. Its transition is the policy's transition name, __SAME_STATE__ for an update that stays in its state, or __INITIALIZE__ (no prior_state) for a create and for an update that moves the resource into that context. A write is invalid in a context when no transition leads from the stored state to the new one (or a restrict_update forbids staying), when a create or move in is in no initial state (WorkflowInvalidInitialStateError), or when the new or stored content meets the conditions of more than one state (WorkflowAmbiguousStateError). transitions is a read-only mapping (types.MappingProxyType, shared by every receiver; copy it with dict() to change it) of every context the stored resource or the new content is in, where a policy applies, to the write's TransitionData there (None if invalid there): a transition where the resource stays, __INITIALIZE__ where it enters, and __LEAVE__ (no proposed_state; prior_state is the state it left) where it leaves. A save of an instance whose row is not on the database written to (a copy with save(using=...)) is reported as a create.

Only API writes are checked against the workflow, so only a save that skipped the check (the admin, ResourceRegistration, server code) can be invalid: it is saved anyway, reported as above, and each context where it is invalid is logged as a WARNING on the scrud_django.workflow logger (before scrud_post_save is sent, so a receiver that raises cannot suppress it), naming the resource's pk, its type URI, the context, the policy and the error (with the states the content meets, when it meets several). Such a save still reads the policy of every context it concerns, and fails (ImproperlyConfigured) where one has several stored policies or an invalid one, as an API write does.

The requesting user is not passed: read it from a contextvars.ContextVar that a middleware sets (see the example below), since receivers and actions run in the request's thread.

Actions are delivered:

  • At most once. An action waits in the connection's in-memory list of on_commit callbacks: a crash between the COMMIT and the call loses it, and nothing retries it. One that raises is logged (below) and dropped.
  • Synchronously, in the thread that wrote, after the commit: in a request, before the response, so a slow action (SMTP, an HTTP call) adds to the request's latency. Outside a transaction an action runs at once.
  • In write order, per database connection.
  • With the live instance: changes made to it after the write, in the same transaction, are visible. Rely on transition_data, or snapshot what you need in a scrud_post_save receiver.

The signals are sent by Resource.save() and delete() (the API, ResourceRegistration, the admin's change and delete pages) and, for each resource it deletes, by a Resource.objects queryset's delete() (bulk deletes, the admin's "delete selected"). QuerySet.update(), bulk_create() and bulk_update() send none. Nor does a raw save: loaddata and a django-reversion revert (Version.revert()) call save_base(raw=True), and as in Django, loading data runs no side effects. To act on a revert, connect a receiver to Django's post_save for Resource, which they send with raw=True (loaddata too).

A setting that is not a list or tuple of paths to mappings stops the process at startup (ImproperlyConfigured). manage.py check reports a type's entry that is not a mapping (scrud_django.E007), a key other than on_save and on_delete (E008) and a value that is neither callable nor None (E009); check --database <alias> warns about a type URI that is not a registered resource type (W006). At write time such an entry runs nothing and never fails the write. Neither does an action that raises: it is logged, with its traceback, on the scrud_django.workflow_actions logger, naming the action, the type URI, on_save or on_delete and the resource's pk.

The signals and the actions' runner live in scrud_django.core.signals (scrud_django.scrud_signals remains an alias of it). The actions are run by a scrud_django.core.signals.ScrudSignalProcessor, which reads the setting again when it changes (override_settings in tests). One processor receives the signals at a time (a fixed dispatch_uid, held strongly): building another one, such as an instance of a subclass in the ready() of an app listed after scrud_django, replaces the default one instead of running each action twice.

An event that must not be lost belongs in a transactional outbox: a receiver stores it in a table in the write's own transaction, so it commits or rolls back with the write, and a worker delivers it later, at least once:

# myapp/models.py
from django.db import models


class OutboxEvent(models.Model):
    resource_pk = models.BigIntegerField()
    type_uri = models.TextField()
    action = models.CharField(max_length=6)  # CREATE, UPDATE or DELETE
    transition = models.JSONField(null=True)
    user_id = models.BigIntegerField(null=True)
    content = models.JSONField(null=True)
    sent_at = models.DateTimeField(null=True)


# myapp/outbox.py, imported in your AppConfig.ready()
import dataclasses
from contextvars import ContextVar

from django.db import router, transaction
from django.dispatch import receiver
from django.utils import timezone
from scrud_django.core.signals import scrud_post_delete, scrud_post_save

from .models import OutboxEvent

current_request = ContextVar("current_request", default=None)


def current_request_middleware(get_response):  # add it to MIDDLEWARE
    def middleware(request):
        token = current_request.set(request)
        try:
            return get_response(request)
        finally:
            current_request.reset(token)

    return middleware


@receiver([scrud_post_save, scrud_post_delete], dispatch_uid="myapp.outbox")
def store_event(sender, instance, using, resource_type_uri, action, **kwargs):
    transition = kwargs.get("transition_data")
    # DRF sets the user it authenticates on the Django request too.
    user = getattr(current_request.get(), "user", None)
    OutboxEvent.objects.using(using).create(
        resource_pk=kwargs.get("pk", instance.pk),  # pk: sent for a delete
        type_uri=resource_type_uri,
        action=action,
        transition=dataclasses.asdict(transition) if transition else None,
        user_id=user.pk if user is not None and user.is_authenticated else None,
        content=instance.content,
    )


def send_events(deliver, batch=100):
    """Run by a worker (cron, Celery beat). `deliver` must be idempotent
    (keyed on the event's pk): an event is sent again if marking it fails.
    store_event writes each event where its write went (`using`): route
    OutboxEvent's writes to the alias scrud_django's models are written to,
    so that this reads them there, not from a replica."""
    using = router.db_for_write(OutboxEvent)
    with transaction.atomic(using=using):
        events = (
            OutboxEvent.objects.using(using)
            .select_for_update(skip_locked=True)
            .filter(sent_at=None)
            .order_by("pk")[:batch]
        )
        for event in events:
            deliver(event)
            event.sent_at = timezone.now()
            event.save(using=using, update_fields=["sent_at"])

Migrating to 0.17.0: the switch to django-ninja

include("scrud_django.urls") serves the ninja API from 0.17.0 (see The API (django-ninja)): the same routes, answering as the DRF ones did, from scrud_django.ninja.api(types=[]) in the URL namespace scrud, and scoped-rbac's semantic documents at semantic/. What to do:

  • To stay on DRF, install scrud-django[drf] and include scrud_django.drf.urls where you included scrud_django.urls (with hsr_urls(), as before; see Staying on DRF). Nothing else changes for your DRF routes. A project that registers its own types with registration.resource_types(...) beside include("scrud_django.urls") is on DRF: switch that include, or move the types to api(types=[registration.json_resource_type_spec(...)]). Left as it was, every request of those types fails (500: their links reverse the DRF routes of the built-in types, json-schema-detail and json-ld-detail, which only scrud_django.drf.urls has), and manage.py check reports it (scrud_django.E011).

  • Old import paths of the DRF adapter (scrud_django.views, scrud_django.exceptions.scrud_exception_handler, ...) keep working for this release with a DeprecationWarning: see Migrating to 0.17.0: the DRF adapter.

  • Leaving DRF without the drf extra, remove what needs it, or a clean install fails at startup (ModuleNotFoundError): rest_framework, rest_framework.authtoken and django_filters from INSTALLED_APPS, the REST_FRAMEWORK setting, and the include(hsr_urls()) of scrudful.rest_framework (the ninja API serves its own HTTP Schema Resources). Keep SCRUDFUL["BASE_URL"]: the ninja API's HTTP Schema Resources need it (scrud_django.W009).

  • REST_FRAMEWORK settings no longer apply to /api/. Of them, the ninja API reads URL_FORMAT_OVERRIDE (the ?format= parameter) and, with DRF installed, NON_FIELD_ERRORS_KEY (the key of the 400 a body that is not a JSON object gets with UNIFORM_ERRORS off, as DRF's serializer answers it). DEFAULT_VERSIONING_CLASS stops applying: links built through scrud_django.reverse follow request.versioning_scheme, which only DRF's views set. Those that change what scrud's DRF routes did:

    • DEFAULT_AUTHENTICATION_CLASSES: on ninja the session's user is the user, and a Basic or token client is anonymous; a token-only API now accepts a session cookie. To keep those clients as they are, set SCOPED_RBAC = {..., "NINJA_USER": "scrud_django.drf.auth.drf_user"} (DRF installed), which runs your DRF authenticators on each ninja request. While a scrud ninja API is routed, manage.py check warns (scrud_django.W008) about authentication classes other than DRF's default pair (session, Basic) unless NINJA_USER is set.

    • DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES: the ninja API is not rate limited unless you say so; manage.py check warns (scrud_django.W008) while a scrud ninja API is routed and DEFAULT_THROTTLE_CLASSES is set. Stay on DRF, or build your own api() (in place of scrud_django.urls) with ninja's throttles, which api() passes to NinjaAPI: api(types=[...], throttle=[UserRateThrottle("100/min")]) (ninja.throttling; a 429 once the rate is spent), then silence scrud_django.W008 (SILENCED_SYSTEM_CHECKS) if you keep the setting for DRF routes of your own. UserRateThrottle keys a request by Django's request.user (else the client's address); ninja's AnonRateThrottle and AuthRateThrottle key by request.auth, which scrud's routes never set, so they treat every request as anonymous.

    • DEFAULT_RENDERER_CLASSES: ninja negotiates among DRF's default renderers' media types whatever the setting says (follow-up ninja-renderer-settings), and never answers text/html: DRF's browsable API is gone from /api/, which answers JSON whatever Accept asks. A project that changed the renderers stays on DRF.

    • EXCEPTION_HANDLER: the ninja API answers errors as scrud's handler does (problem details); a handler of your own wrapping it is not run. Stay on DRF to keep it.

    • DEFAULT_PERMISSION_CLASSES: scrud's DRF routes set IsAuthorized themselves, and scoped-rbac's DRF role routes took the setting (the IsAuthorized above); on ninja every route asks the grants itself, as IsAuthorized does. A stricter permission of your own on the role routes is not run on ninja: stay on DRF to keep it.

    DEFAULT_PARSER_CLASSES, DEFAULT_PAGINATION_CLASS and PAGE_SIZE change nothing: scrud's and scoped-rbac's DRF routes set their own JSON parser and paginators (100 a page by default, ?page_size= up to 1000), which the ninja API follows.

  • One API per namespace. An app that builds its own api() includes it instead of scrud_django.urls, not beside it: Django reverses the namespace scrud within its first include only, so the other API's requests fail (500), and manage.py check reports it (scrud_django.E010). Give a second API its own urls_namespace. Code that reverses scrud's route names on ninja qualifies them with the namespace (reverse("scrud:services"), "scrud:<slug>-list"); on DRF they are unqualified, as before.

  • A branch's JSON, which a published branch's prefix answered before 0.17.0, is the studio's /api/ui-branch-items/<branch>/ (with scrud_django.ui.studio installed); the prefix serves the UI's pages only.

Migrating to 0.17.0: the UI app

The UI is now its own Django app, served at the site root, and /api/ serves JSON only. If you use scrud_django.ui:

# urls.py (the root URLconf)
urlpatterns = [
    path("api/", include("scrud_django.urls")),
    ...,  # your own URLs
    path("", include("scrud_django.ui.urls")),  # last, no namespace argument
]

Add that last line, last (it claims only the slugs of the types it serves, so it does not swallow your other URLs), and delete your own path("studio/", include("scrud_django.ui.studio.urls")): the UI's URLconf includes the studio at studio/ (namespace scrud-studio) itself. The pages' route names are scrud_ui:list (slug) and scrud_ui:detail (slug, pk). What changes:

  • HTML is no longer served under /api/. /api/<slug>/ answers JSON for every Accept (DRF's browsable API still answers a browser's Accept on a DRF route; ninja answers JSON). A resource's page is at /<slug>/<pk>/. Links, bookmarks and hx-gets that expected HTML at /api/... need the UI path (/todo-lists/7/).
  • htmx writes go to the UI's URLs and answer HTML (the re-rendered frame, the refused-PUT form, the 412 and 409 reload).
  • Prefixes are UI only. A published branch's prefix serves the UI's pages; there is no JSON under it. JSON is at /api/, where Scrud-UI-Branch or ui-branch selects a branch within main's tree only; every item a branch shows is the studio's /api/ui-branch-items/<branch>/.
  • A branch cannot be published at the UI's base / (a 400; the system check scrud_django_ui.W001 warns about a stored one). / is always main's UI, so a site that used a restricted branch at / as a gate for the whole site loses that gate.
  • Pages and the studio authenticate with Django's session user only. DRF's Basic and Token authentication no longer apply to them (they still apply to /api/). CSRF is enforced on their writes even without CsrfViewMiddleware, an anonymous tokenless POST gets Django's CSRF 403, and OPTIONS on a page or a studio endpoint is a 405 with Allow. A page sends no Link header, and the JSON body of a page's write is subject to DATA_UPLOAD_MAX_MEMORY_SIZE.
  • Types the UI cannot serve. A computed type registered only with a DRF viewset_class (no compute=) has no UI page and cannot be embedded. The pages read through the core, which asks a type's grants and its neutral checks= and object_checks= hooks, not the permission classes of a custom viewset_class or IsAuthorized subclasses (DRF-only authorization). So the UI refuses a type registered with a custom viewset_class: its pages, embeds, prefixes and studio previews answer 404, and the system check scrud_django_ui.W003 names it. So does a type whose API routes you built by hand rather than through registration. To serve it again, declare its rules as both checks= and object_checks=, or, when the viewset adds no authorization of its own, register it with ui_authorization="core" (see "Hooks on json_resource_type").
  • Stored component templates. in_mount(...), embed(...) and api_url(...) with /api/ paths keep working (they are mapped to the UI), but a raw hx-get="/api/..." that expects HTML now gets JSON: use in_mount, embed or the UI path.
  • Tests of UI pages sign in with a session (client.force_login(user)), not DRF's force_authenticate, which pages do not read.

Migrating to 0.17.0: the DRF adapter

scrud's DRF views, serializers, filters, permissions and exception handler moved to the scrud_django.drf package. The old import paths keep working for this release: each is the moved module (or object) itself, so isinstance checks and your subclasses are unaffected, and importing it raises a DeprecationWarning naming the new path. Change your imports:

Old path New path
scrud_django.views scrud_django.drf.views
scrud_django.computed.ComputedResourceViewSet scrud_django.drf.computed
scrud_django.computed.computed_etag (and computed_answer, computed_link, not_modified) scrud_django.core.computed
scrud_django.filters scrud_django.drf.filters
scrud_django.paginations scrud_django.drf.paginations
scrud_django.permissions scrud_django.drf.permissions
scrud_django.renderers scrud_django.drf.renderers
scrud_django.serializers scrud_django.drf.serializers
scrud_django.mixins.serializer_mixins scrud_django.drf.serializers
scrud_django.mixins.view_mixins scrud_django.drf.mixins
scrud_django.drf_requirements scrud_django.drf.requirements
scrud_django.ui.views, scrud_django.ui.branches.views scrud_django.drf.ui
scrud_django.validators.WorkflowValidator (and narrow_of, view_of, rbac_permissions_of) scrud_django.drf.validators
scrud_django.exceptions.scrud_exception_handler, as_drf, drf_errors scrud_django.drf.exceptions

scrud_django.validators and scrud_django.exceptions stay: their neutral names (the JSON Schema validator, the errors) import from there without a warning; only the DRF names in the table warn. scrud_django.computed names its moved objects one by one too: its neutral helpers resolve to scrud_django.core.computed's, with the warning, even without DRF. The logger names (scrud_django.permissions, scrud_django.validators) are unchanged. Set the exception handler to its new path (the old value still resolves, with the warning):

REST_FRAMEWORK = {
    ...,
    "EXCEPTION_HANDLER": "scrud_django.drf.exceptions.scrud_exception_handler",
}

The DRF routes are scrud_django.drf.urls; include("scrud_django.urls") serves the ninja API from this release (see Migrating to 0.17.0: the switch to django-ninja). Importing scrud_django.drf without DRF installed raises an ImportError naming scrud-django[drf]. To find the old paths in your code, run your tests with -W "error:scrud_django:DeprecationWarning". To serve DRF's Basic and token clients on ninja too, see scrud_django.drf.auth.drf_user in The API (django-ninja).

Upgrading

Version 0.15.0 refuses workflow writes whose content (new or stored) meets more than one state; policies with two transitions for one pair of states or a state in both initial_states and states; an update in place of a restrict_update state through a transition whose from or to lists other states too (only a transition from that state to itself alone allows it); and POST or PUT @actions of your viewsets (and views that are not viewsets) for a role whose only grant there is conditioned on scrud_workflow (403: give it a grant that is not). It adds keyword arguments to scrud_post_save, makes TransitionData immutable, runs on_delete actions for bulk deletes, fails a server-side save closed on duplicate policies, or an invalid one, in any context it concerns, and logs failed actions on scrud_django.workflow_actions and invalid server-side saves on scrud_django.workflow. Run manage.py check --database <alias> for each database and work through the Upgrading list of the 0.15.0 release notes before upgrading.

Version 0.14.0 adopts django-scoped-rbac 0.12 and scrudful 0.10, which change OPTIONS (a 204 linking an HTTP Schema Resource) and need the hsr_urls() include, SCRUDFUL["BASE_URL"] and a scoped-rbac migration. Work through the Upgrading list of the 0.14.0 release notes before upgrading.

Version 0.12.0 has breaking changes (Django 5.2, uv, scrudful 0.8, scoped-rbac 0.11, JSON-only bodies, object-level RBAC on detail routes, RBAC-filtered lists with new migrations to run, workflow policies in every context, 428 for a missing precondition and new ETags, problem details for errors, a superuser-only admin). Stop every 0.11 process before you migrate. Work through the Upgrading list of the 0.12.0 release notes before upgrading.

Development Get Started

Development uses uv.

uv sync
uv run pre-commit install

Confirm setup

make test
make lint
make migrations-check

Build the documentation with make docs.

Start the demo application

cd demo
uv run python manage.py migrate
uv run python manage.py createsuperuser
uv run python manage.py runserver

The demo serves ninja alone (no DRF) at http://127.0.0.1:8000/api/, which has no root page: try /api/services/. Resource routes need a login (anonymous requests get 401): sign in at http://127.0.0.1:8000/accounts/login/ (Django's own login view, a session that the API, the UI and the studio read) with the superuser. The API takes no Basic auth. The superuser may do everything; other users need scoped-rbac roles (api/roles/, api/role-assignments/). The Django admin is at http://127.0.0.1:8000/admin/. The demo reads DJANGO_SECRET_KEY, DJANGO_DEBUG and DJANGO_ALLOWED_HOSTS from the environment; its defaults (a public development key, DEBUG on, localhost only) are for running it locally, and with DEBUG off it needs a key of its own.

The manage.py at the repository root runs on the in-memory test settings (nothing persists): use it for check and the migrations check only. With SCRUD_TEST_PG_HOST set (see tests/settings.py) it uses that PostgreSQL server's SCRUD_TEST_PG_NAME database (default scrud) instead, where writes persist; likewise SCRUD_TEST_MYSQL_HOST for a MySQL or MariaDB server.

To run the suite on MySQL or MariaDB, add the driver, which builds against the MySQL client library (not a dev dependency):

SCRUD_TEST_MYSQL_HOST=127.0.0.1 SCRUD_TEST_MYSQL_PASSWORD=... \
  uv run --with mysqlclient==2.3.0 pytest

Metadata

Release files for scrud-django 0.17.0

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

Source distribution (sdist)

Source distribution for scrud-django 0.17.0
File Size Uploaded Provenance Actions
scrud_django-0.17.0.tar.gz 516.2 kB Without provenance Details for scrud_django-0.17.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for scrud-django 0.17.0
File Interpreter ABI Platform Actions
scrud_django-0.17.0-py3-none-any.whl Python 3 none any Details for scrud_django-0.17.0-py3-none-any.whl

Total release size: 1.1 MB

Release files / scrud_django-0.17.0.tar.gz

Download URL scrud_django-0.17.0.tar.gz
Size 516.2 kB
Tags Source
SHA-256 checksum
How to use checksums
5905d8c65c028bdeabd1eb76bbfb48f3f55840e0a34af8b5afcca0e14797527b
BLAKE2b-256 checksum
How to use checksums
990bfcc93f768e2fdef28980c098e057b3cb6fab02978faecef8c78258a934a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / scrud_django-0.17.0-py3-none-any.whl

Download URL scrud_django-0.17.0-py3-none-any.whl
Size 598.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6c06d5a9c55d338df50c61148b41fa6cf5bbd3c3922992705d16a6f7c8990cd8
BLAKE2b-256 checksum
How to use checksums
a171e01966d80be5a2b2bbf86de0f628b09b02191a3a6468a216f28aa7b93463
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for scrud-django 0.17.0

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.17.0 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