通过django restful api上传文件

时间:2017-05-03 00:10:48

标签: python django curl django-rest-framework restful-architecture

我已经阅读了所有的stackoverflow问题和答案以及我找到的每个教程,但我仍然无法让它工作 - 我可能会愚蠢。我正在尝试通过curl通过restful api将文件上传到django。我的curl命令如下

curl -X POST -H "Content-Type:multipart/form-data" -u alex:password123 -F "docfile=@/Users/Alex/test.txt" http://127.0.0.1:8000/files/

models.py

from django.db import models

class File(models.Model):

     title = models.CharField(max_length=100, default='')
     docfile = models.FileField(upload_to='file/')

views.py

from rest_framework.parsers import FormParser, MultiPartParser
from models import File
from serializers import FileSerializer

class UploadFile(viewsets.ModelViewSet):
     queryset = File.objects.all()
     serializer_class = FileSerializer
     parser_classes = (MultiPartParser, FormParser,)


     def preform_create(self, serializer):
          file_obj = self.request.FILES['docfile'] 
          serializer.save(file_obj)

serializers.py

from rest_framework import serializers
from models import File

class FileSerializer(serializers.HyperlinkedModelSerializer):

     class Meta:
         model = File
         fields = ('docfile','name')

urls.py

from django.conf.urls import url, include
from rest_framework import routers
from quickstart import views

router = routers.DefaultRouter()
router.register(r'files', views.UploadFile)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

我的媒体根目录是MEDIA_ROOT = ''我已经阅读了大量的文档,但我真的被困在所有这些如何融合在一起/我缺少什么。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

REST API的一个优点是它附带了大量的类来减少您为常见操作编写的代码,但如果您不熟悉API并且您将通过curl上传文件也许你应该从更简单的东西开始:

class UploadFile(views.APIView):
    parser_classes = (parsers.FormParser, parsers.MultiPartParser)

    def post(self, request):
        if len(request.FILES) > 0:
            request_file = request.FILES[0]
            file = File(docfile=request_file, title='something')
            file.save()
        else:
           # do something

urls.py:

url(r'^files/$', views.UploadFile.as_view(), name='files'),

掌握API提供的不同视图后,您可以尝试viewsets.ViewSet。我个人更喜欢从views.APIView扩展我的观点,并对代码有更多的控制权。