使用Django编写文件上传API

时间:2023-01-27 11:53:56

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.

我有一个Django应用程序,它围绕着用户上传文件,我正在尝试创建一个API。基本上,我们的想法是可以将一个POST请求(例如使用curl)与文件一起发送到我的应用程序,该应用程序将接受数据并处理它。

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.

如何让Django侦听并接受这样的文件?Django的所有文件上传文档都是围绕处理从Django的表单中上传的文件进行的,所以我不确定如何将文件发送出去。

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

如果我能提供更多的信息,我很乐意。任何能让我开始的事都将不胜感激。

1 个解决方案

#1


10  

Create a small view which ignores every method but POST and make sure it does not have CSRF protection:

创建一个忽略除了POST以外的所有方法的小视图,并确保它没有CSRF保护:

from django import forms

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

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

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

@csrf_exempt
def upload_file(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed('Only POST here')

    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

参见:将REST添加到Django。

#1


10  

Create a small view which ignores every method but POST and make sure it does not have CSRF protection:

创建一个忽略除了POST以外的所有方法的小视图,并确保它没有CSRF保护:

from django import forms

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

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

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

@csrf_exempt
def upload_file(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed('Only POST here')

    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

参见:将REST添加到Django。