【发布时间】:2016-12-25 21:27:26
【问题描述】:
我在 Django 中有一些 REST API 端点,我想将 the same authentication 用于 Graphene。 documentation 不提供任何指导。
【问题讨论】:
标签: python django rest authentication graphql
我在 Django 中有一些 REST API 端点,我想将 the same authentication 用于 Graphene。 documentation 不提供任何指导。
【问题讨论】:
标签: python django rest authentication graphql
例如,如果您在 API 视图中使用 authentication_classes = (TokenAuthentication,),则可以将端点添加到以这种方式装饰的 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 端点并保留了 GraphiQL 工具使用的原始 ^graphql。
然后,您应该在 GraphQL 客户端中设置 Authorization 标头并指向 graphql_token 端点。
更新:请参阅this GitHub issue,人们在其中提出了替代解决方案和完整的工作示例。
【讨论】:
添加一些我在遵循此集成时必须采取的额外步骤:
class RTGraphQLView(GraphQLView):
def parse_body(self, request):
if type(request) is rest_framework.request.Request:
return request.data
return super().parse_body(request)
Graphene 期待 .body attr,但 DRF 会读取它并将其附加到 .data,然后再传递给 GraphQLView。
【讨论】: