-5

I have a Rails app server. I want to build a Python client that uploads an image.

I want to do something like this:

def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        json    = {
            'entry': {
                'entry_id': entry_id,
            }
        },
        files   = {
            "entry['photo']": (
                os.path.basename(image_path),
                open(image_path, 'rb'),
                'image/jpg',
                {'Expires': '0'}
            )
        }
    )

I need the image nested into the 'entry' key. The above code does not work because the key "entry['photo']" isn't valid.

How do I do this?

Thank you so much for your help!

JPN
  • 632
  • 12
  • 24
  • If you're going to down vote this, please tell me why? Thanks! – JPN Jun 02 '17 at 14:00
  • It's not clear what you're asking for. Do you want to see rails code that accepts an image, or python code that sends it, or both? It would also help if you described what have you tried, where, specifically you are roadblocked, and any error messages are you getting. – Troy Jun 04 '17 at 08:56
  • Let me know if the question edits is clear. Thanks! – JPN Jun 04 '17 at 14:52
  • You have **one** request body stream. You can't put both JSON and files in that (the two arguments are mutually exclusive). You'll either have to stick to only a multipart body (where some of the parts can contain JSON) or to just JSON (and encode the image in a way that it can be transferred via JSON). It doesn't matter here that you used a files name that may or may not be interpretable as a Python dictionary key reference. – Martijn Pieters Jun 05 '17 at 09:36
  • None of this is really Python `requests` or Rails specific however. – Martijn Pieters Jun 05 '17 at 09:36

2 Answers2

0

Comment: I need the key of the image to be entry['photo'].

What you want to do results in invalid dict. The following is from docs.python-requests.org

files = {'photo': ('test.jpg', open('test.jpg', 'rb'), 'image/jpg', {'entry_id': entry_id, 'Expires': '0'})}

From SO Answer Upload Image using POST form data in Python-requests

files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
stovfl
  • 14,998
  • 7
  • 24
  • 51
  • In this example, the key of the image is `media`. I need the key of the image to be `entry['photo']`. I need the image to be two levels deep. – JPN Jun 04 '17 at 14:53
  • Yes, invalid dict...this is the problem. How do i resolve this? – JPN Jun 04 '17 at 21:58
0

I figured it out:

def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        files   = {
            'entry[entry_id]': (None, entry_id, 'text'),
            'entry[photo]': (os.path.basename(image_path), open(image_path, 'rb'), 'image/jpg', {'Expires': '0'})
        }
    )
JPN
  • 632
  • 12
  • 24