【问题标题】:How do you upload a file with a POST request on django-tastypie? [duplicate]如何在 django-tastypie 上上传带有 POST 请求的文件? [复制]
【发布时间】:2012-12-16 15:24:26
【问题描述】:

可能重复:
Django-tastypie: Any example on file upload in POST?

我目前像这样向我的 API 发出 cURL POST 请求

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"username":"theusername", "api_key":"anapikey", "video_title":"a title", "video_description":"the description"}' http://localhost:8000/api/v1/video/ 

但现在我需要能够将视频文件添加到上传中。关于使用 Tastypie 上传文件的问题,我已经四处寻找了几个小时,但我没有提出一个可靠的回应。我需要添加 Base64 编码吗?如果有怎么办?使用 POST 请求上传文件后,如何访问该文件?只是正常的 request.FILES 动作?我不希望将文件保存到数据库,只是获取文件的路径。

#Models.py
class Video(models.Model):
    video_uploader = models.ForeignKey(User)
    video_path = models.CharField(max_length=128)
    video_views = models.IntegerField(default=0)
    upload_date = models.DateTimeField(auto_now_add=True)
    video_description = models.CharField(max_length=860)
    video_title = models.SlugField()

我对如何为 Tastypie 实施文件上传系统感到非常困惑,因此非常感谢任何帮助。谢谢!

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    这是通过MultiPartdjango-tastypie 上传文件的方法。

    Models.py

    class Video(models.Model):
        video_uploader = models.ForeignKey(User)
        video = models.FileField(_('Video'), upload_to='path_to_folder/') # save file to server
        video_views = models.IntegerField(default=0)
        upload_date = models.DateTimeField(auto_now_add=True)
        video_description = models.CharField(max_length=860)
        video_title = models.SlugField()
    

    Api.py

    class MultipartResource(object):
        def deserialize(self, request, data, format=None):
            if not format:
                format = request.META.get('CONTENT_TYPE', 'application/json')
            if format == 'application/x-www-form-urlencoded':
                return request.POST
            if format.startswith('multipart'):
                data = request.POST.copy()
                data.update(request.FILES)
                return data
            return super(MultipartResource, self).deserialize(request, data, format)
    
    class VideoResource(MultipartResource, ModelResource):
       """
       Inherit this Resource class to `MultipartResource` Class
       """
       # Assuming you know what to write here 
       ...
    

    然后通过CURL

    curl -H "Authorization: ApiKey username:api_key" -F "video=/path_to_video/video.mp3" -F "video_title=video title" http://localhost:8000/api/v1/video/ -v
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2018-12-13
      • 2018-06-25
      • 2021-08-10
      • 1970-01-01
      • 2012-08-25
      • 2012-10-04
      相关资源
      最近更新 更多