Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask FileStorage object to File Object

Tags:

python

io

flask

I have made an api through flask which submit a file and after receiving it on the back end , I want to further upload this to an unknown server using python requests module

The server accepts the file if I do this like -

requests.post(urlToUnknownServer,files={'file':open('pathToFile')})

Now my requirement is to get the file param uploaded through flask.
In flask I get the file as FileStorage object. I don't want to save this on my server, instead directly wants it to upload further.
So basically I want to convert that FileStorage object to return type of open() function which is file(please correct me here if I am wrong)

I had tried it using -

obj=file(request.files['fileName'].read().encode('string-escape'))
requests.post(urlToUnknownServer,files={'file':obj})

This doesn't work. Can it be possible to do that without saving file on my server.

like image 211
sagar Avatar asked Sep 11 '16 15:09

sagar


2 Answers

Maybe you can use read() without encoding it. such as this:

obj=request.files['fileName'].read()
requests.post(urlToUnknownServer,files={'file':obj})
like image 133
T . Tom Cat Avatar answered Sep 19 '22 06:09

T . Tom Cat


For anyone stuck with same problem, just convert to BufferedReader

like this:

    from io import BufferedReader
    image = request.files.get('name')
    image.name = image.filename
    image = BufferedReader(image)

and then you can post it

    requests.post(urlToUnknownServer,files={'file' : image})
like image 36
Dmitry Shchedrov Avatar answered Sep 21 '22 06:09

Dmitry Shchedrov