سؤال

I am trying to send an HTTPS PUT request to a RESTful API Django web service using a djangorestframework (DRF: http://django-rest-framework.org/) View. I cannot get this to work due to Django's Cross Site Request Forgery (CSRF) protection.

The PUT request is intended to allow unauthenticated users to add a resource.

What I have considered/tried:

  1. Disabling CSRF -- not acceptable. The API runs on the same Django instance as the non-API service. Disabling CSRF protection is too much risk.
  2. Using the X-Requested-With: XMLHttpRequest header on the PUT request (I control the clients). Doesn't work -- I still get the CSRF error.
  3. Using the @crsf_exempt decorator on the PUT view. I would if I could -- the framework defines a class, not a view.

My current best option is to write PUT views myself without using DRF's View class. I can then use the @crsf_exempt decorator successfully.

I'd like to use DRF's View class -- but cannot see how. Can you?

هل كانت مفيدة؟

المحلول

Thanks to James Cran Wellward, I was also able to solve this issue by using the method_decorator.

class ExampleView(ResponseMixin,View):
  renderers=DEFAULT_RENDERERS
  def get(self,request):
    response=Response(200,{'msg':'called via GET'})
    return self.render(response)
  def post(self,request):
    response=Response(200,{'msg':'called via POST'})
    return self.render(response)
  @method_decorator(csrf_exempt):
  def dispatch(self,*args,**kwargs):
    return super(EampleView,self).dispatch(*args,**kwargs)

and then test it:

curl -X GET http://www.example.com/rest/exampleview/

returns:

{msg: 'called via GET'}

and

curl -X POST http://www.example.com/rest/exampleview/

returns:

{msg: 'called via POST'}

HTH. see the original post.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top