python-backend by jiatastic/open-python-skills
npx skills add https://github.com/jiatastic/open-python-skills --skill python-backend适用于 FastAPI、SQLAlchemy 和 Upstash 的生产就绪 Python 后端模式。
src/
├── auth/
│ ├── router.py # 端点
│ ├── schemas.py # pydantic 模型
│ ├── models.py # 数据库模型
│ ├── service.py # 业务逻辑
│ └── dependencies.py
├── posts/
│ └── ...
├── config.py
├── database.py
└── main.py
# 错误 - 阻塞事件循环
@router.get("/")
async def bad():
time.sleep(10) # 阻塞!
# 良好 - 在线程池中运行
@router.get("/")
def good():
time.sleep(10) # 在同步函数中没问题
# 最佳 - 非阻塞
@router.get("/")
async def best():
await asyncio.sleep(10) # 非阻塞
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
username: str = Field(min_length=3, max_length=50, pattern="^[a-zA-Z0-9_]+$")
age: int = Field(ge=18)
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
payload = decode_token(token)
user = await get_user(payload["sub"])
if not user:
raise HTTPException(401, "User not found")
return user
@router.get("/me")
async def get_me(user: User = Depends(get_current_user)):
return user
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield session
from upstash_redis import Redis
redis = Redis.from_env()
@app.get("/data/{id}")
def get_data(id: str):
cached = redis.get(f"data:{id}")
if cached:
return cached
data = fetch_from_db(id)
redis.setex(f"data:{id}", 600, data)
return data
from upstash_ratelimit import Ratelimit, SlidingWindow
ratelimit = Ratelimit(
redis=Redis.from_env(),
limiter=SlidingWindow(max_requests=10, window=60),
)
@app.get("/api/resource")
def protected(request: Request):
result = ratelimit.limit(request.client.host)
if not result.allowed:
raise HTTPException(429, "Rate limit exceeded")
return {"data": "..."}
详细模式请参阅:
| 文档 | 内容 |
|---|---|
references/fastapi_patterns.md | 项目结构、异步、Pydantic、依赖项、测试 |
references/security_patterns.md | JWT、OAuth2、密码哈希、CORS、API 密钥 |
references/database_patterns.md | SQLAlchemy 异步、事务、预加载、迁移 |
references/upstash_patterns.md | Redis、速率限制、QStash 后台作业 |
每周安装量
932
仓库
GitHub 星标数
3
首次出现
Jan 24, 2026
安全审计
安装于
opencode897
codex890
gemini-cli889
github-copilot883
cursor869
kimi-cli853
Production-ready Python backend patterns for FastAPI, SQLAlchemy, and Upstash.
src/
├── auth/
│ ├── router.py # endpoints
│ ├── schemas.py # pydantic models
│ ├── models.py # db models
│ ├── service.py # business logic
│ └── dependencies.py
├── posts/
│ └── ...
├── config.py
├── database.py
└── main.py
# BAD - blocks event loop
@router.get("/")
async def bad():
time.sleep(10) # Blocking!
# GOOD - runs in threadpool
@router.get("/")
def good():
time.sleep(10) # OK in sync function
# BEST - non-blocking
@router.get("/")
async def best():
await asyncio.sleep(10) # Non-blocking
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
username: str = Field(min_length=3, max_length=50, pattern="^[a-zA-Z0-9_]+$")
age: int = Field(ge=18)
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
payload = decode_token(token)
user = await get_user(payload["sub"])
if not user:
raise HTTPException(401, "User not found")
return user
@router.get("/me")
async def get_me(user: User = Depends(get_current_user)):
return user
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield session
from upstash_redis import Redis
redis = Redis.from_env()
@app.get("/data/{id}")
def get_data(id: str):
cached = redis.get(f"data:{id}")
if cached:
return cached
data = fetch_from_db(id)
redis.setex(f"data:{id}", 600, data)
return data
from upstash_ratelimit import Ratelimit, SlidingWindow
ratelimit = Ratelimit(
redis=Redis.from_env(),
limiter=SlidingWindow(max_requests=10, window=60),
)
@app.get("/api/resource")
def protected(request: Request):
result = ratelimit.limit(request.client.host)
if not result.allowed:
raise HTTPException(429, "Rate limit exceeded")
return {"data": "..."}
For detailed patterns, see:
| Document | Content |
|---|---|
references/fastapi_patterns.md | Project structure, async, Pydantic, dependencies, testing |
references/security_patterns.md | JWT, OAuth2, password hashing, CORS, API keys |
references/database_patterns.md | SQLAlchemy async, transactions, eager loading, migrations |
references/upstash_patterns.md | Redis, rate limiting, QStash background jobs |
Weekly Installs
932
Repository
GitHub Stars
3
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode897
codex890
gemini-cli889
github-copilot883
cursor869
kimi-cli853
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
Gemini Interactions API 指南:统一接口、智能体交互与服务器端状态管理
833 周安装
Apollo MCP 服务器:让AI代理通过GraphQL API交互的完整指南
834 周安装
智能体记忆系统构建指南:分块策略、向量存储与检索优化
835 周安装
Scrapling官方网络爬虫框架 - 自适应解析、绕过Cloudflare、Python爬虫库
836 周安装
抽奖赢家选取器 - 随机选择工具,支持CSV、Excel、Google Sheets,公平透明
838 周安装
Medusa 前端开发指南:使用 SDK、React Query 构建电商商店
839 周安装