4

I am trying to convert a .png image to string and send it through django api but it causes error

from django.shortcuts import render
from django.http import HttpResponse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import base64

# Create your views here.
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt

def get_res(request):
    if request.method == 'POST':
        x = json.loads(request.body)
        arrx = x['x']
        arry = x['y']
        plt.plot(arrx,arry)
        plt.savefig('plot.png')
        with open('plot.png', 'rb') as imageFile:
            str = base64.b64encode(imageFile.read())
        response = json.dumps([{'image': str}])
        return HttpResponse(response, content_type = 'text/json')

This causes error

Internal Server Error: /
Traceback (most recent call last):
  File "C:\lol\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
  File "C:\lol\myenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
  File "C:\lol\myenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\lol\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
  File "C:\lol\apiex\api1\views.py", line 23, in get_res
response = json.dumps([{'image': str}])
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

Please tell me hoe to resolve this , or if there is a better way to do this.

Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
Dipesh Sinha
  • 93
  • 11

1 Answers1

4

You should use .decode() to convert the binary string to a string:

@csrf_exempt
def get_res(request):
    if request.method == 'POST':
        x = json.loads(request.body)
        arrx = x['x']
        arry = x['y']
        plt.plot(arrx,arry)
        plt.savefig('plot.png')
        with open('plot.png', 'rb') as imageFile:
            data = base64.b64encode(imageFile.read()).decode()
        response = json.dumps([{'image': data}])
        return HttpResponse(response, content_type = 'text/json')

This is a base64 string, so you will have to "decode" the string to an image at the client side, like demonstrated here.

Note: do not name variables with class names, since it will "shadow" the reference to the class.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555