Mike Crittenden
Mike Crittenden

Reputation: 5917

Writing a file upload API using Django

I have a Django app that revolves around users uploading files, and I'm attempting to make an API. Basically, the idea is that a POST request can be sent (using curl for example) with the file to my app which would accept the data and handle it.

How can I tell Django to listen for and accept files this way? All of Django's file upload docs revolve around handling files uploaded from a form within Django, so I'm unsure of how to get files posted otherwise.

If I can provide any more info, I'd be happy to. Anything to get me started would be much appreciated.

Upvotes: 10

Views: 5079

Answers (1)

Udi
Udi

Reputation: 30472

Create a small view which accepts only POST and make sure it does not have CSRF protection:
forms.py

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

views.py

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse, HttpResponseServerError

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

@csrf_exempt
@require_POST
def upload_file(request):            
    form = UploadFileForm(request.POST, request.FILES)
    if not form.is_valid():
        return HttpResponseServerError("Invalid call")
        
    handle_uploaded_file(request.FILES['file'])
    return HttpResponse('OK')

See also: Adding REST to Django

Upvotes: 11

Related Questions