问题描述
Graphene-Django docs 请注意,如果您不想使用 GraphiQL API 浏览器,您可以在实例化 graphiql=False
时传递 GraphQLView
。但是,我希望保持 GraphiQL API 浏览器可用,并且仅限制谁可以访问它。怎么做?
例如,我将如何做到只有“员工”用户(可以访问管理站点)才有权访问 GraphiQL 浏览器?
解决方法
您可以扩展 Graphene-Django GraphQLView
并覆盖其 can_display_graphiql
方法(定义为 here)以添加此类逻辑。
from graphene_django.views import GraphQLView as BaseGraphQLView
class GraphQLView(BaseGraphQLView):
@classmethod
def can_display_graphiql(cls,request,data):
# Only allow staff users to access the GraphiQL interface
if not request.user or not request.user.is_staff:
return False
return super().can_display_graphiql(request,data)
然后在您的 urls.py 文件中,使用新的 GraphQLView
而不是默认的:
# import the GraphQLView defined above
urlpatterns = [
# ...
path("graphql",GraphQLView.as_view(graphiql=True)),]