Amir Afianian
Amir Afianian

Reputation: 2807

how can I provide csrf protection in case of using requests module to post data to a django view

I have a modelForm as follows:

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = FileUploads
        fields = ['uploads']

and a view like so:

@csrf_exempt
def upper(request):
    form = UserProfileForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return HttpResponse(status=200)
    return HttpResponse(status = 403)

And I have a simple script to send a multipart/encoded file to the view as such:

import requests
f = open('C:\\Users\\myname\\Desktop\\image.jpg', 'rb')
urls='http://localhost:8000/upper'
r=requests.post(urls, files= {'uploads':f})
print(r.status_code)

My question being: everything works fine as long as I have the csrrf_exempt decorator above the receiving view, that's fine for test environment. But what if I wanted the csrf protection in place? Considering the fact that I'm using requests module, how can I provide the csrf token?

Upvotes: 1

Views: 566

Answers (1)

knbk
knbk

Reputation: 53719

You need to pass a cookie and a header with the same value:

import requests
f = open('C:\\Users\\myname\\Desktop\\image.jpg', 'rb')
urls='http://localhost:8000/upper'
cookies = {'csrftoken': 'token'}
headers = {'X-CSRF-TOKEN': 'token'}
r=requests.post(urls, files={'uploads':f}, cookies=cookies, headers=headers)
print(r.status_code)

The value of the token does not matter, you can take any literal, as long as they are the same.

Upvotes: 1

Related Questions