4

suppose I want to post an image file with some metadata to a web service and then save that file to a location somewhere. How do I do it? I have seen examples of posting data and examples of getting data from a request but can't get anything working which does both, which means I can't verify either. So here's one variation of the code I culled from a samples I found here and another here:

import requests
import json
import cv2
import shutil

content_type = 'image/jpeg'
headers = {'content-type': content_type}
addr = 'http://127.0.0.1:5000'
test_url = addr + '/step/Update-Image'
path = 'D:/Temp/TrainingPics'
inFile = "/Drew16.jpg"
outFile = "/Test.jpg"

image_metadata = {'UserId': 'test', 'Type': 'test2'}
data = {'name': 'drew16.jpg', 'data': json.dumps(image_metadata)}
files = {'media': open(path + inFile, 'rb')}
r = requests.post(test_url, files=files, data=image_metadata)

if r.status_code == 200:
    with open(path + outFile, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

I get a status code 200 but the output file is corrupted and I can't see where to pull the metadata. Where am I going wrong here? Any help would be appreciated.

ds_practicioner
  • 733
  • 8
  • 20
  • What's `test_url` and how will it response? – Waket Zheng Jun 10 '18 at 03:51
  • The file already exists locally, so why do you need to copy it at all? Does the server response contain a modified version of the file? – John Gordon Jun 10 '18 at 03:52
  • test_url is just the call to the web service. What I really want to do is have a remote camera pass me an image which I want to use in facial recognition software. I can't seem to verify whether I am passing an image correctly because I can't recover it. I can't test either the post of the file or the corresponding read unless they both work. – ds_practicioner Jun 10 '18 at 04:15

0 Answers0