Strawberry+FastAPI:如何在依赖项中获取请求信息?
如何在Strawberry GraphQL的依赖项中获取请求信息?
你可以直接在依赖函数中注入FastAPI的Request对象,FastAPI会自动将当前请求实例传递给依赖。以下是修改后的完整代码:
import strawberry from fastapi import FastAPI, Depends, Request, WebSocket, BackgroundTasks from strawberry.types import Info from strawberry.fastapi import GraphQLRouter def custom_context_dependency(request: Request = Depends()) -> str: # 这里可通过request获取请求头,示例提取Authorization头 auth_header = request.headers.get("Authorization") # 替换为你的业务逻辑,此处仅做示例返回 return auth_header or "John" def has_root_access(request: Request = Depends()) -> bool: # 从请求头获取用户信息并判断权限 user_role = request.headers.get("X-User-Role") # 示例逻辑:角色为admin则返回True return user_role == "admin" async def get_context( custom_value=Depends(custom_context_dependency), has_root_access=Depends(has_root_access), ): return { "custom_value": custom_value, "has_root_access": has_root_access, } @strawberry.type class Query: @strawberry.field def example(self, info: Info) -> str: return f"Hello {info.context['custom_value']}" schema = strawberry.Schema(Query) graphql_app = GraphQLRouter( schema, context_getter=get_context, ) app = FastAPI() app.include_router(graphql_app, prefix="/graphql")
关键说明:
- 在
custom_context_dependency和has_root_access函数的参数中添加request: Request = Depends(),FastAPI会自动注入当前请求对象 - 通过
request.headers可访问所有请求头,根据业务需求提取对应字段(如认证令牌、用户角色等) - 同步依赖(示例中的两个函数)和异步依赖均支持这种注入方式,无需额外配置
内容的提问来源于stack exchange,提问作者npk
相关产品推荐
相关产品推荐

