2016-08-18 194 views

回答

15

例如,如果您使用的是您的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(['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')), 
# ... 

請注意,我們添加了一個新的端點並保留了GraphiQL工具使用的原始^graphql

然後,您應該在您的GraphQL客戶端中設置Authorization標頭,並指向graphql_token端點。

+0

這是否仍適用於您?我試圖用SessionAuthentication來做同樣的事情,但是當它試圖讀取請求的主體時,我從graphene-django得到一個錯誤? – Joe

+0

仍然有效,但我沒有最新的軟件包版本。我的回答用: Django的== 1.8.3 djangorestframework == 3.2.2 Django的graphiql == 0.4.4 石墨烯== 0.10.2 graphql核心== 0.5.3 graphql-Django的視圖= = 1.3 graphql-relay == 0.4.4 –

3

並稱,我有以下這種整合時要採取一些額外的步驟:

class RTGraphQLView(GraphQLView): 

def parse_body(self, request): 
    if type(request) is rest_framework.request.Request: 
     return request.data 
    return super().parse_body(request) 

石墨烯期待.body ATTR但DRF讀取它,並傳遞給GraphQLView之前它重視.data