Failed post Image & data Using Requests DRF

Viewed 105

I want to submit text values alongside an image to an API. Another API using django-rest-framework.

I did this,

from PIL import Image       
from io import BytesIO
os.environ['NO_PROXY'] = '127.0.0.1'
response = requests.get(url_logo)
site_logo = Image.open(BytesIO(response.content))
files = {'site_logo':site_logo}
profile_payload = {"name":"Mark Johnson", "address":"dave str.blvd"}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
requests.post(profile_url, data=profile_payload, files=files, headers=headers, 
timeout=conn_timeout, stream=True)

I got this error.

TypeError: a bytes-like object is required, not 'PngImageFile'

Serializer:

class AddProfile(serializers.Serializer):
    name = serializers.CharField(required=True, max_length=150)
    address = serializers.CharField(required=True, max_length=100)
    site_logo = serializers.ImageField(required=False)

I changed the site_logo to this:

site_logo = BytesIO(response.content)

Then it broke down totally by timing out and given me connection peer reset error.

What am I missing?

1 Answers

Actually it's all in the error,

TypeError: a bytes-like object is required, not 'PngImageFile'

You're supposed to send a bytes-like object and not a PngImageFile.response.content is already a bytes-like object. So, all you have to do is:

import requests
os.environ['NO_PROXY'] = '127.0.0.1'
response = requests.get(url_logo)
site_logo = response.content #<<----Made a change here
files = [('site_logo',('<logo-name>',site_logo))] #<<-----made a change here too
profile_payload = {"name":"Mark Johnson", "address":"dave str.blvd"}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
requests.post(profile_url, data=profile_payload, files=files, headers=headers, 
timeout=conn_timeout, stream=True)

Do let me know if this works out for you.

Related