如何将Graphene GraphQL框架与Django REST框架一起使用

发布于 2021-01-29 15:06:34

我在Django中有一些REST API端点,我想对Graphene使用相同的身份验证。该文档不提供任何指导。

关注者
0
被浏览
72
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    例如,如果authentication_classes = (TokenAuthentication,)在API视图中使用,则可以将端点添加到以这种方式装饰的GraphQLView中:

    urls.py:

    # ...
    from rest_framework.authentication import TokenAuthentication
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.decorators import authentication_classes, permission_classes, api_view
    
    def graphql_token_view():
        view = GraphQLView.as_view(schema=schema)
        view = permission_classes((IsAuthenticated,))(view)
        view = authentication_classes((TokenAuthentication,))(view)
        view = api_view(['GET', 'POST'])(view)
        return view
    
    urlpatterns = [
    # ...
        url(r'^graphql_token', graphql_token_view()),
        url(r'^graphql', csrf_exempt(GraphQLView.as_view(schema=schema))),
        url(r'^graphiql', include('django_graphiql.urls')),
    # ...
    

    请注意,我们添加了一个新的^graphql_token端点,并保留^graphql了GraphiQL工具使用的原始端点。

    然后,您应该Authorization在GraphQL客户端中设置标头并指向graphql_token端点。


    更新:请参阅此GitHub问题,其中人们提出了替代解决方案和完整的工作示例。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看