如何在Django中序列化(JSON)FileField [英] How to serialize(JSON) FileField in Django

查看:87
本文介绍了如何在Django中序列化(JSON)FileField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,正在尝试构建一个应用程序来测试我的项目中的一些内容.我想阅读表单-做一些验证,然后将输入发送到另一个模块(例如,单独运行的调度程序).将使用表单数据(即文件)调用调度程序rest api,调度程序会将数据加载到模型中.我在调用其余api之前使用python请求并将数据序列化为json.这就是我出错的地方.Django在request.FILES上创建一个InMemoryUploadedFile类,该类将数据加载到内存中的某个位置,并将其序列化为Json并不容易.我尝试寻找其他方式(例如图像序列化器示例),但无法解决此问题.

I am new to Django and trying to build an app to test out few things for my project. I want to read the form - do some validation and then send the input to another module (say a scheduler running separately). The scheduler rest api will be called with the form data (which is file) and the scheduler will load the data into the models. I am using python requests and serializing data into json before calling the rest api. This is where I am getting error. Django on request.FILES create a InMemoryUploadedFile class which has the data loaded somewhere in memory and serializing this to Json is not straightforward. I tried looking other ways (like image serializers example) but not able to resolve this issue.

forms.py

class UploadDatasetForm(forms.Form):
    docfile = forms.FileField(label='Choose file')

views.py

def test_upload(request):
    if request.method == 'POST':
        form = UploadDatasetForm(request.POST, request.FILES)
        if form.is_valid():
            in_file = request.FILES['docfile']
            payload = {'doc_file': in_file}
            msg = json.dumps(payload)
            URL = 'http://localhost:8880/form'
            r = requests.post(URL, data=msg)
    return HttpResponse(json.dumps(r.text), content_type="application/json")

错误:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <InMemoryUploadedFile: A_test.csv (text/csv)> is not JSON serializable

这里的任何帮助将不胜感激.非常感谢.

Any help here will be appreciated. Thanks a lot.

推荐答案

您似乎正在尝试序列化对InMemoryUploadedFile实例的引用-如果您只想对数据进行JSON序列化而不是整个类实例,则可以读取数据.

It looks like you're trying to serialize a reference to an InMemoryUploadedFile instance - if you just want to JSON serialize the data and not the whole class instance you could read the data.

替换:

payload = {'doc_file': in_file}

使用

payload = {'doc_file': in_file.read()}

如果数据很大,您将要确保使用chunks():

You'll want be sure to use chunks() if the data is large: https://docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.chunks

这篇关于如何在Django中序列化(JSON)FileField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆