2. Share a check between actions
A task title must contain something besides spaces. Preparing a task and previewing it should enforce the same rule. Attach one dependency to both actions so each caller gets that check automatically.
This program reuses NewTask, TaskDraft, and title normalization from
the first step. The new pieces are require_title
and Depends. Save it as docs_src/tutorial/shared_checks.py.
"""Reuse a title check in two actions and reject an empty title."""
import asyncio
from docs_src.quickstart import NewTask, TaskDraft
from docs_src.quickstart import prepare_task as normalize_task
from fastsprout.actions import action
from fastsprout.core import Depends
async def require_title(payload: NewTask) -> None:
if not payload.title.strip():
raise ValueError("Task title cannot be empty")
@action(dependencies=[Depends(require_title)])
async def prepare_task(payload: NewTask) -> TaskDraft:
return await normalize_task(payload)
@action(dependencies=[Depends(require_title)])
async def preview_task(payload: NewTask) -> str:
draft = await normalize_task(payload)
return f"Task: {draft.title}"
async def main() -> None:
payload = NewTask(title=" Write documentation ")
draft = await prepare_task(payload)
print("Prepared:", draft.title)
print("Preview:", await preview_task(payload))
try:
await prepare_task(NewTask(title=" "))
except ValueError as error:
print("Rejected:", error)
if __name__ == "__main__":
asyncio.run(main())
Run it from your tutorial directory:
Result
Prepared: Write documentation
Preview: Task: Write documentation
Rejected: Task title cannot be empty
Why attach a dependency?
Depends(require_title) tells the action to run the check before its body.
The dependency requests payload by the same argument name used in the action.
If the check raises, the action stops and the caller receives the exception.
Both actions reuse the same check and the original normalization operation.
An endpoint or worker calls an action; it does not need to remember to call
require_title separately. Change the rule in one function when the feature's
requirements change.
The try block handles the error for this demonstration. In an application,
the caller decides how to report it, such as a rejected command or an HTTP
error response.
Try giving preview_task an empty title too. Its dependency enforces the same
rule. Next, group these two operations in a service.
Previous: Your first action · Next: Group related operations