Django Rest Framework抱怨CSRF

时间:2015-09-04 13:03:34

标签: python django csrf

我开发了一个简单的Web服务,但是没有使用Django Rest Framework的帖子,因为它抱怨CSRF:

  

“detail”:“CSRF失败:未设置CSRF cookie。”

删除api_view装饰器确实会阻止消息显示但是我将无法访问request.data。我认为api_view确实检查了CSRF,尽管我添加了csrf_exempt装饰器。

这是我的观点:

@permission_classes((IsAuthenticated, ))
@csrf_exempt
@api_view(['POST'])
def get_stats(request):
    """
    Returns the stats available.
    """

    user = request.user

    if request.method == 'POST':
        serializer = StatsRequestSerializer(data=request.data)
        stats_request = serializer.data
        return JSONResponse(stats_request)

            #serializer = QuizSerializer(user.quizes.all(), many=True)
            #return JSONResponse(serializer.data)

    response = ActionResponse(status='error', error='Invalid request')
    serializer = ActionResponseSerializer(response)
    return JSONResponse(serializer.data, status=400)

这是我的模特:

class StatsRequest(models.Model):
    """
    A model which describes a request for some stats for specific users.
    """

    start_date = models.DateField()
    end_date = models.DateField()

这是我的请求POST:

{"start_date" : "1992-01-15", "end_date" : "1992-01-15" }

有什么想法吗?

更多信息:

AUTHENTICATION_BACKENDS = (
    'social.backends.facebook.FacebookOAuth2',
    'social.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend'
)

3 个答案:

答案 0 :(得分:1)

请看这个链接:
Disabling CSRF checking in Django

答案 1 :(得分:0)

所以,在试图解决这个问题几个小时后,我终于做到了。 跟踪DRF和Django的源代码让我相信我需要为此找到一个解决方法,因为即使关闭了CSRF验证也是明确的,可能是在api_view装饰器上进行了CSRF检查。所以我只是创建了自己的装饰器:

from functools import wraps
from django.utils.decorators import available_attrs, decorator_from_middleware

def csrf_clear(view_func):
    """
    Skips the CSRF checks by setting the 'csrf_processing_done' to true.
    """

    def wrapped_view(*args, **kwargs):
        request = args[0]
        request.csrf_processing_done = True
        return view_func(*args, **kwargs)

    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)

以及我对新装饰器的看法:

@csrf_clear
@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
def get_stats(request):
    """
    Returns the stats available.
    """

    user = request.user

    if request.method == 'POST':
        serializer = StatsRequestSerializer(data=request.data)

        if serializer.is_valid():
            stats_request = serializer.data
            return JSONResponse(stats_request)

            #serializer = QuizSerializer(user.quizes.all(), many=True)
            #return JSONResponse(serializer.data)

    response = ActionResponse(status='error', error='Invalid request')
    serializer = ActionResponseSerializer(response)
    return JSONResponse(serializer.data, status=400)

答案 2 :(得分:0)

urls.py

from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
    url(r'^snippets/$', views.SnippetList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+)/$', csrf_exempt(views.SnippetDetail.as_view())),

views.py

from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
class SnippetList(APIView):
    @csrf_exempt
    @need_post_parameters([PARAM_MESSAGE_OBJ])
    def post(self, request, *args, **kwargs):
        data = request.POST.get(PARAM_MESSAGE_OBJ)

        try:
            message_obj = json.loads(data)
        except Exception as e:
            return HttpResponseBadRequest(error_json("Could not parse JSON"))

http://www.chenxm.cc/post/509.html