How to serialize (JSON) FileField in Django

I am new to Django and am trying to create an application to check out a few things for my project. I want to read the form - do some validation, and then submit it to another module (say, the scheduler works separately). The rest api scheduler will be called with the form data (which is the file), and the scheduler will load the data in the model. I am using python requests and serializing data in json before calling rest api. Here I get the error. Django upon request. FILES creates an InMemoryUploadedFile class that loads data somewhere in memory, and serializing this in Json is not easy. I tried looking for other ways (for example, an example of an image serializer), but could not solve this problem.

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") 

Error:

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

Any help here would be appreciated. Thank you very much.

+5
source share
2 answers

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

Replace:

 payload = {'doc_file': in_file} 

WITH

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

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

+2
source

By default, python only supports hand transforms that are full of standard data types (str, int, float, dict, list, etc.). You are trying to convert InMemoryUploadedFile, the dump function does not know how to handle this. What you need to do is provide a way to convert data into one of the data types supported by python.

 class MyJsonEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, InMemoryUploadedFile): return o.read() return str(o) msg = json.dumps(payload, cls=MyJsonEncoder) 
+1
source

Source: https://habr.com/ru/post/1269731/


All Articles