You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:15:43