无法从strawberry.fastapi导入GraphQL,求技术解决方案
解决Strawberry FastAPI中
ImportError: cannot import name 'GraphQL' from 'strawberry.fastapi'的问题 问题原因
Strawberry版本迭代后,strawberry.fastapi模块下的GraphQL类已被重命名为GraphQLRouter,你参考的教程使用了旧版API,而当前安装的是新版Strawberry,因此出现导入错误。
修复步骤
- 替换导入类:将原导入语句中的
GraphQL改为GraphQLRouter - 更新实例化代码:用
GraphQLRouter替代GraphQL创建路由实例 - 简化路由注册:新版
GraphQLRouter已整合HTTP和WebSocket路由,无需分别调用add_route和add_websocket_route,直接用include_router注册即可
修改后的完整代码
from fastapi import FastAPI import strawberry from strawberry.fastapi import GraphQLRouter @strawberry.type class Book: title: str author: str price: int @strawberry.type class Query: @strawberry.field def book(self) -> Book: return Book(title="Computer Fundamentals", author="Sinha", price=300) schema = strawberry.Schema(query=Query) graphql_app = GraphQLRouter(schema) app = FastAPI() app.include_router(graphql_app, prefix="/book")
验证方法
重新执行命令:
uvicorn Mystrawberry:app --reload
访问http://localhost:8000/book即可正常使用GraphQL playground。
内容的提问来源于stack exchange,提问作者KansaiRobot
相关产品推荐
相关产品推荐

