扫描二维码
关注或者微信搜一搜:编程智域 前端至全栈交流与成长
发现1000+提升效率与开发的AI工具和实用程序:https://tools.cmdragon.cn/
使用Ariadne作为GraphQL实现库,配合FastAPI的异步特性:
# 安装依赖库
pip install fastapi==0.95.2 uvicorn==0.21.1
pip install ariadne==0.19.1 python-multipart==0.0.6
推荐采用分层架构:
project/
├── main.py
├── schemas/
│ └── graphql/
│ ├── query.py
│ ├── mutation.py
│ └── subscription.py
└── models/
└── pydantic_models.py
流程图解:
示例代码实现:
from ariadne import QueryType, gql, make_executable_schema
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
query = QueryType()
@query.field("getUser")
async def resolve_get_user(_, info, user_id: int):
# 实际应替换为数据库查询
return User(id=user_id, name="John", email="john@example.com")
type_defs = gql("""
type Query {
getUser(userId: Int!): User
}
type User {
id: Int!
name: String!
email: String!
}
""")
schema = make_executable_schema(type_defs, query)
数据验证流程:
graph LR A[输入参数] --> B{Pydantic验证} B -->|通过| C[业务处理] B -->|拒绝| D[返回422错误] C --> E[持久化存储] E --> F[返回结果]
用户创建示例:
from ariadne import MutationType
mutation = MutationType()
class UserInput(BaseModel):
name: str
email: str
@mutation.field("createUser")
async def resolve_create_user(_, info, input: dict):
user_data = UserInput(**input).dict()
# 插入数据库逻辑
return {"id": 1, **user_data}
type_defs += gql("""
input UserInput {
name: String!
email: String!
}
type Mutation {
createUser(input: UserInput!): User
}
""")
from fastapi import WebSocket
from ariadne.types import ExtensionSync
class SubscriptionExtension(ExtensionSync):
def resolve(self, event, _):
return event.get("result")
@app.websocket("/subscriptions")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
# 实现订阅逻辑
from ariadne import SubscriptionType
subscription = SubscriptionType()
@subscription.source("newMessage")
async def generate_messages(obj, info):
while True:
await asyncio.sleep(5)
yield {"content": f"Message {time.time()}"}
type_defs += gql("""
type Subscription {
newMessage: String!
}
""")
如何优化GraphQL查询性能?
当出现"Field 'email' of type 'String!' is not found"错误时,应检查什么?
@scalar("CustomDate")
def parse_date_value(value):
try:
return datetime.fromisoformat(value)
except ValueError:
raise GraphQLError("Invalid date format")
余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
,阅读完整的文章:FastAPI与GraphQL的完美邂逅:如何打造高效API?
参与评论
手机查看
返回顶部