fastapi-startup-and-shutdown-events

fastapi-startup-and-shutdown-events is a cursor rule for Cursor from holtwood/awesome-cursorrules-zh. It costs 8 tokens per session (814 once invoked), scanned A, original, MIT.

Rules for running setup tasks when a FastAPI application starts and cleanup tasks when it stops, such as opening database connections, loading configuration, or starting background tasks.

In plain words
What is it for?
Use it to initialise databases, caches, configuration, or other shared resources before requests arrive and clean them up during shutdown.
Why use it?
It gives application resources a defined place to be prepared and released.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

Good fit Use it to initialise databases, caches, configuration, or other shared resources before requests arrive and clean them up during shutdown.

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/holtwood/awesome-cursorrules-zh

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for fastapi-startup-and-shutdown-events

README.md
[![agentmods](https://agentmods.dev/badge/rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events/github.svg)](https://agentmods.dev/rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events)
Your own site
<a href="https://agentmods.dev/rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events"><img src="https://agentmods.dev/badge/rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for fastapi-startup-and-shutdown-events

Your own site · 80×15
<a href="https://agentmods.dev/rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events"><img src="https://agentmods.dev/badge/rules/holtwood/awesome-cursorrules-zh/fastapi-startup-and-shutdown-events.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 8 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 814 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00008 $0.00814
Opus 5 $0.00004 $0.00407
Sonnet 5 $0.00002 $0.00163
Haiku 4.5 $0.00001 $0.00081

Measured 6d ago against content hash dcb1f0ab938d, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-09, from the pricing page.

Security

Grade A, and why

fastapi-startup-and-shutdown-events scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 6d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

docs/rules/backend/python/fastapi-api-example/fastapi-startup-and-shutdown-events.mdc · 107 lines

How it starts

The opening of the file, as written. The whole thing — 107 lines — stays where its author put it; the contents beside it link to each section on GitHub.

FastAPI 启动和关闭事件

本规则集定义了在 FastAPI 应用程序中如何利用启动 (startup) 和关闭 (shutdown) 事件来执行初始化和清理任务,确保应用程序的健壮性和资源管理的正确性。

1. 启动事件 (Startup Events)

启动事件在应用程序开始接收请求之前执行。这对于初始化数据库连接、加载配置、创建后台任务或执行其他一次性设置非常有用。

1.1 使用 @app.on_event("startup") 装饰器

您可以使用 @app.on_event("startup") 装饰器来注册启动函数。这些函数可以是同步的也可以是异步的。

from fastapi import FastAPI
import asyncio

app = FastAPI()

# 模拟数据库连接
db_connection = None

@app.on_event("startup")
async def startup_event():
    global db_connection
    print("Application starting up...")
    # 模拟异步数据库连接
    await asyncio.sleep(1) 
    db_connection = {"status": "connected"}
    print("Database connected.")

@app.get("/")
async def read_root():
    if db_connection and db_connection["status"] == "connected":
        return {"message": "Hello World", "db_status": "connected"}
    return {"message": "Hello World", "db_status": "disconnected"}

1.2 多个启动事件

您可以注册多个启动事件。它们将按照注册的顺序执行。

@app.on_event("startup")
async def load_config():
    print("Loading configuration...")
    await asyncio.sleep(0.5)
    print("Configuration loaded.")

@app.on_event("startup")
async def init_cache():
    print("Initializing cache...")
    await asyncio.sleep(0.5)
    print("Cache initialized.")

2. 关闭事件 (Shutdown Events)

关闭事件在应用程序停止接收请求并即将关闭时执行。这对于关闭数据库连接、释放资源、清理临时文件或执行其他清理任务非常有用。

2.1 使用 @app.on_event("shutdown") 装饰器

您可以使用 @app.on_event("shutdown") 装饰器来注册关闭函数。这些函数可以是同步的也可以是异步的。

@app.on_event("shutdown")
async def shutdown_event():
    global db_connection
    print("Application shutting down...")
    # 模拟异步关闭数据库连接
    if db_connection:
        await asyncio.sleep(1)
        db_connection = None
        print("Database connection closed.")
    print("Application shut down.")

2.2 多个关闭事件

您可以注册多个关闭事件。它们将按照注册的顺序执行。

@app.on_event("shutdown")
async def save_logs():
    print("Saving logs before shutdown...")
    await asyncio.sleep(0.5)
    print("Logs saved.")

@app.on_event("shutdown")
async def close_queue_connection():
    print("Closing message queue connection...")
    await asyncio.sleep(0.5)
    print("Message queue connection closed.")

Read the full file on GitHub · 107 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 6d ago First seen · 107 lines · 8 tokens per session scan A dcb1f0ab938d

Subscribe to this mod's changes

fastapi-startup-and-shutdown-events is a cursor rule published in the GitHub repository holtwood/awesome-cursorrules-zh (233 stars, last pushed 1mo ago), licensed MIT. It adds 8 tokens to every session and 814 once invoked, about $0.0000 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.