Approval Workflows in Python: Rules Before Routes
An approval button looks simple. The behavior behind it usually is not: who may approve, which states allow approval, and what happens when the request is submitted twice?
Consider a fictional purchase-request application. The requester submits a draft; a different user with review permission approves or rejects it. This is a useful example of business software because the difficult part is preserving the rules across every entry point: a web form, an API, a scheduled job, or an import.
This tutorial develops the rule layer in ordinary Python. It is an illustrative example, independent of any employer system.
Start with the transitions
The first design artifact can be a small table:
| Current state | Allowed next state | Required actor |
|---|---|---|
| Draft | Submitted | The requester |
| Submitted | Approved | A different user with review permission |
| Submitted | Rejected | A different user with review permission |
| Approved or rejected | None in this example | Nobody |
This table makes several decisions explicit. There is no direct draft-to-approved path. A requester cannot approve their own request. A completed review cannot silently become a draft again.
Real applications may need withdrawal, resubmission, delegation, or multiple approval levels. Those are additional transitions with their own rules, rather than exceptions hidden in a route handler.
Keep the rule layer small
Save the following as workflow.py. It uses only the Python standard library and works with Python 3.10 or later.
from dataclasses import dataclass, replace
from decimal import Decimal
from enum import Enum
class State(str, Enum):
DRAFT = "draft"
SUBMITTED = "submitted"
APPROVED = "approved"
REJECTED = "rejected"
class InvalidTransition(ValueError):
pass
@dataclass(frozen=True)
class Request:
owner_id: int
amount: Decimal
state: State = State.DRAFT
ALLOWED = {
State.DRAFT: {State.SUBMITTED},
State.SUBMITTED: {State.APPROVED, State.REJECTED},
State.APPROVED: set(),
State.REJECTED: set(),
}
def transition(request, target, *, actor_id, can_review=False):
if target not in ALLOWED[request.state]:
raise InvalidTransition(
f"Cannot move from {request.state.value} to {target.value}"
)
if target == State.SUBMITTED:
if actor_id != request.owner_id:
raise PermissionError("Only the requester may submit")
if not request.amount.is_finite() or request.amount <= 0:
raise ValueError("Amount must be finite and positive")
elif not can_review or actor_id == request.owner_id:
raise PermissionError("An independent reviewer is required")
return replace(request, state=target)
Enum gives the states named values. A frozen dataclass makes this example return a new request rather than mutate the input. Neither feature supplies business validation automatically: the transition function still has to enforce the policy. See the Python references for enumerations and dataclasses.
The function has no database connection, HTTP response, or email client. That keeps a policy change easy to test without starting the rest of the application.
The caller must supply authenticated identity and trusted review permissions. Accepting actor_id or can_review directly from a client request would defeat the policy. Input parsing must also convert and validate the amount and target state before calling this function.
Test the decisions, including refusals
Save this beside it as test_workflow.py:
import unittest
from decimal import Decimal
from workflow import InvalidTransition, Request, State, transition
class WorkflowTests(unittest.TestCase):
def setUp(self):
self.draft = Request(owner_id=7, amount=Decimal("42.50"))
self.pending = transition(
self.draft, State.SUBMITTED, actor_id=7
)
def test_submission_does_not_mutate_the_draft(self):
self.assertEqual(self.draft.state, State.DRAFT)
self.assertEqual(self.pending.state, State.SUBMITTED)
def test_an_independent_reviewer_can_approve(self):
result = transition(
self.pending, State.APPROVED, actor_id=9, can_review=True
)
self.assertEqual(result.state, State.APPROVED)
def test_requester_cannot_approve_even_with_review_permission(self):
with self.assertRaises(PermissionError):
transition(
self.pending, State.APPROVED,
actor_id=7, can_review=True,
)
def test_review_permission_is_required(self):
with self.assertRaises(PermissionError):
transition(self.pending, State.REJECTED, actor_id=9)
def test_a_draft_cannot_skip_submission(self):
with self.assertRaises(InvalidTransition):
transition(
self.draft, State.APPROVED, actor_id=9, can_review=True
)
def test_invalid_amounts_cannot_be_submitted(self):
for value in ("0", "-1", "NaN", "Infinity"):
with self.subTest(amount=value):
with self.assertRaises(ValueError):
transition(
Request(7, Decimal(value)),
State.SUBMITTED, actor_id=7,
)
Run python -m unittest -v. The tests check observable decisions: permitted transitions, rejected transitions, separation of duties, and input validity. They do not depend on how the function organizes its branches. The standard library's unittest documentation explains discovery, assertions, and subtests.
A pure function does not solve concurrent writes
Two workers can load the same submitted request, independently pass these rules, and both attempt to save a result. Correct local logic is only one layer of correctness.
The persistence layer needs a transaction and a concurrency strategy, such as a conditional update against the expected state or a version number. It must also enforce authorization for the stored record. If the update affects no rows, reload or report a conflict rather than pretending the operation succeeded.
Persist the state change and its audit entry together. If approval triggers an external notification, decide how that notification will be retried without sending it twice; a database transaction cannot roll back an email already delivered.
The companion tutorial on PostgreSQL constraints and safe retries explores the database side of this boundary.
Questions to ask in a code review
Before accepting an approval feature, check the paths that do not involve clicking its button:
- Can an API call bypass the transition policy?
- Can a requester supply another user's identity or permissions?
- Can an import write an impossible state?
- Can two workers complete the same transition?
- Does an unsuccessful transition leave an audit entry or notification behind?
The feature is ready when its rules remain understandable and enforceable across those paths. A short transition table and focused tests give the rest of the implementation a clear contract.
The views expressed on this website are my own and do not necessarily reflect the views of Oracle. Nothing published here is written on behalf of, endorsed by, or reviewed by my employer.