1
votes

What is the problem Here ?

I got an error shows

ValueError: too many values to unpack

This code process is to get all available images in a folder then put that images location into an array. Then create an other array called files and add image location with specific format and send the POST request to the API

import requests
import logging
import os
import json

try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

url_and = "https://api.test.com/api/3.0/listings/"

android_token = '68as76df87s86df7asd76f87as6df78sfd'
headers = {
    'Authorization': "Token " + android_token,
    'platform': 'android'
}

data_android = {
    'mailing_details':'3',
    'abcoupay':'false',
    'price':'55.00',
    'description':'Test description',
    'title':'TEST drill machine and others.',
    'meetup':'false',
    'condition':'2',
    'mailing':'true',
    'collection_id':'24'
}

urls = []
for file in os.listdir(os.getcwd()+"/product_images"):
    if file.endswith((".jpg",".jpeg",".png",".JPG",".JPEG",".PNG")):
        x = os.getcwd()+"\\"+file
        urls.append(x)

files = []
x = 0
for file in urls:
    files.append("'photo_"+str(x)+"': ('image_"+str(x)+".jpg', open('"+file+"', 'rb'), 'image/jpeg')")
    x+=1

# files = {
#             'photo_0': ('image_0.jpg', open('E:/products files/Drill machine/1.jpg', 'rb'), 'image/jpeg'),
#             'photo_1': ('image_1.jpg', open('E:/products files/Drill machine/2.jpg','rb'), 'image/jpeg')        
#         }

response = requests.request("POST", url_and,data=data_android,files=files,headers=headers)
print(response.text.encode("utf-8"))

Error

Traceback (most recent call last):
  File "cookies.py", line 102, in <module>
    response = requests.request("POST", url_and,data=data_android,files=files,headers=headers)
  File "C:\python27\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\python27\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "C:\python27\lib\site-packages\requests\sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\python27\lib\site-packages\requests\models.py", line 316, in prepare
    self.prepare_body(data, files, json)
  File "C:\python27\lib\site-packages\requests\models.py", line 504, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "C:\python27\lib\site-packages\requests\models.py", line 141, in _encode_files
    for (k, v) in files:
ValueError: too many values to unpack
2
url_and,data=data_android are you sure about that comma? - GPhilo
files should be passed as a dictionary. I need to find a better example but it's clear from the error that it's expecting a dict - roganjosh

2 Answers

0
votes

Your files should be passed as a dict or a list of tuples and you are not doing that. You could do below,

files.append(("photo_"+str(x), ("image_"+str(x)+".jpg", open(file, "rb"), "image/jpeg")))
0
votes

The files parameter for requests.request should be a dict where the keys are file names and the values are file content or file objects. You should therefore build your files variable as a dict instead:

files = {'image_%s.jpg' % x: open(file, 'rb') for x, file in enumerate(urls)}

If you need the content type as well, you can make the dict values 3-tuples that contain the file name, the file object and the content type:

files = {'image_%s.jpg' % x: ('image_%s.jpg' % x, open(file, 'rb'), 'image/jpeg') for x, file in enumerate(urls)}