1

我有一个模型,我正在为此制作一个美味的 api。我有一个字段存储我手动维护的文件的路径(我没有使用FileField,因为用户没有上传文件)。这是一个模型的要点:

class FooModel(models.Model):
    path = models.CharField(max_length=255, null=True)
    ...
    def getAbsPath(self):
        """
        returns the absolute path to a file stored at location self.path
        """
        ...

这是我的美味派配置:

class FooModelResource(ModelResource):
    file = fields.FileField()

    class Meta:
        queryset = FooModel.objects.all()

    def dehydrate_file(self, bundle):
        from django.core.files import File
        path = bundle.obj.getAbsPath()        
        return File(open(path, 'rb'))

在文件字段的 api 中,这将返回文件的完整路径。我希望tastepie 能够提供实际文件或至少一个文件的url。我怎么做?任何代码片段表示赞赏。

谢谢

4

2 回答 2

4

首先决定如何通过 API 公开您的文件的 URL 方案。您实际上并不需要 file 或 dehydrate_file (除非您想在 Tastypie 中更改模型本身的文件表示)。相反,只需在 ModelResource 上添加一个附加操作。例子:

class FooModelResource(ModelResource):
    file = fields.FileField()

    class Meta:
        queryset = FooModel.objects.all()

    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('download_detail'), name="api_download_detail"),
            ]

    def download_detail(self, request, **kwargs):
        """
        Send a file through TastyPie without loading the whole file into
        memory at once. The FileWrapper will turn the file object into an
        iterator for chunks of 8KB.

        No need to build a bundle here only to return a file, lets look into the DB directly
        """
        filename = self._meta.queryset.get(pk=kwargs[pk]).file
        wrapper = FileWrapper(file(filename))
        response = HttpResponse(wrapper, content_type='text/plain') #or whatever type you want there
        response['Content-Length'] = os.path.getsize(filename)
        return response

获取 .../api/foomodel/3/

返回: { ... 'file' : 'localpath/filename.ext', ... }

获取 .../api/foomodel/3/下载/

返回: ...实际文件的内容...

或者,您可以在 FooModel 中创建一个非 ORM 子资源文件。您必须定义resource_uri(如何唯一标识资源的每个实例),并覆盖 dispatch_detail 以完全执行上述 download_detail 的操作。

于 2012-02-26T15:31:07.867 回答
0

对 FileField 进行的唯一转换是在您返回的内容上查找“url”属性,如果存在则返回该属性,否则它将返回字符串化对象,正如您所注意到的,它只是文件名。

如果要将文件内容作为字段返回,则需要处理文件的编码。你有几个选择:

  • 最简单:使用CharField并使用base64模块将从文件中读取的字节转换为字符串
  • 更通用但功能等效:编写一个自定义的 sweetpie Serializer,它知道如何将 File 对象转换为其内容的字符串表示形式
  • 覆盖get_detail资源的功能以使用任何适当的内容类型仅提供文件,以避免 JSON/XML 序列化开销。
于 2012-02-26T15:27:16.463 回答