polkid
polkid

Reputation: 313

Flask - Post a file with accompying JSON

Is it possible to POST a file to a flask app that has both a file and JSON data accompanying it?

In my initial development, I am doing this via two api endpoints, and it just seems clunky. I'd like to be able to accomplish this using one POST, instead of two.

Is this possible?

Upvotes: 2

Views: 3397

Answers (1)

Muntaser Ahmed
Muntaser Ahmed

Reputation: 4657

Yes, you can POST a file with JSON data accompanying it. For example:

import requests
with open(path_to_file, 'rb') as my_file:
        files = {'file': my_file}
        payload = {'data1': 'foo', 'data2': 'bar'}
        r = requests.post(data=payload, files=files)

There is a lot of useful information regarding Flask and requests (a very nice HTTP lib) here:

  1. http://flask.pocoo.org/docs/0.10/quickstart/#quickstart
  2. http://docs.python-requests.org/en/latest/user/quickstart/

Upvotes: 1

Related Questions