0

On my Django backend, I deal with images like this:

for file in request.FILES.iteritems():
            image = request.FILES["image"]

It is easy to send a post request via java using a byte array.

But how to do a post request using Python?

As in, I've an image url.

I've downloaded the iamge from an url using

r = requests.get('url')
r.content #ImageConent

Now how do I post it such that it is delivered as a byte array?

4
  • Post it where? Do you mean a HTTP POST to another server? Commented Nov 16, 2012 at 12:32
  • Also, your for loop is not necessary. Just execute image = request.FILES["image"] without the loop. Commented Nov 16, 2012 at 12:33
  • I intend to do an HTTP post. Commented Nov 16, 2012 at 12:40
  • I basically have an instagram image url, which I plan to download and send. Commented Nov 16, 2012 at 12:41

1 Answer 1

2

Have a look at the requests documentation on how to send multipart requests. Basically you just need to do:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}   
>>> r = requests.post(url, files=files)

Or in your case:

>>> r = requests.get(url1)
>>> files = {'image': r.content}   
>>> r = requests.post(url2, files=files)
Sign up to request clarification or add additional context in comments.

3 Comments

Except the OP has the image data in memory, not a file. You'd either need to explain how to write it to a file, or how to use something like StringIO() to make it file-like. But we have to establish first and foremost what the OP was intending to do with the image.
MultiValueDictKeyError: "Key 'image' not found in <MultiValueDict: {}>"
that seems to be a problem on your django part. I've just tested file upload using requests to a simpe django view, and it should work like described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.