我正在使用DjangoRestFramework來製作API。目前我有OAuth2認證工作,這意味着我可以生成一個有效的訪問令牌來使用API。DjangoRestFramework上傳文件'CSRF驗證失敗'
如何上傳用戶文件?我需要上傳文件並將其與上傳文件的用戶關聯起來。
我目前正在做這樣
API/views.py:
class FileUploadView(APIView):
parser_classes = (FileUploadParser,)
def put(self, request, filename, format=None):
file_obj = request.FILES['file']
# do stuff
return Response(status=204)
API/urls.py有這樣一行:
url(r'^files/', 'api.views.FileUploadView'),
但是當我嘗試上傳文件我得到一個錯誤,指出:
'CSRF verification failed. Request aborted'
'Reason given for failure: CSRF cookie not set'
當我嘗試這個curl命令:
curl -XPUT http://localhost:8000/files/ -H 'Authorization: Bearer some_access_token' -F [email protected]
這裏是我的REST_FRAMEWORK默認:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.OAuth2Authentication',
)
}
見https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#exceptions – user1168095