Search code examples
pythonhttpserverrequestxlsx

How can I display/save an xlsx file that I received from a server with http requests in python?


I am building an application where data is sent to a server, the server creates an xlsx (excel) file with that data and returns that file to the client where at the end I want it to be displayed

Im using flask and the creation of the file itself with the data from the client works and the file is saved locally in the same folder. I tried several things but I cant seem to check wether the file was sent back correctly because I dont exactly know how to work with it on the client side. Currently I try sending the file back as following:

return send_file("my_file.xlsx", as_attachment=True)

and I also tried

return send_file("absolute/path/to/my_file", as_attachment=True)

On the client side I also tried all kind of things and Im currently at

print(r.content)

which prints tons of characters, backslashes etc..

and where r is

r = requests.get('http://127.0.0.1:5000/', params = {...}) 

So two problems:

  1. I dont know if the file is correctly sent from the server, how can I check?

  2. Probably answers the first one: How can I display or save the file on the client side?

The file is created with xlsxwriter and I dont get any error messages. Return status also is 200 so I guess my problem is opening the file on the client side. But if anybody has advice I would be really happy to hear!

Edit: File was sent correctly, the answer was:

r = requests.get('http://127.0.0.1:5000/', params = {...}) 
def save_xl(r):
    with open('file.xlsx', 'wb') as f:
        f.write(r.content)
    
save_xl(r)

And the file was create successfully


Solution

  • you can try saving the content of the request as a xlsx file.

    r = requests.get('http://127.0.0.1:5000/', params = {...}) 
    def save_xl(r):
        with open('file.xlsx', 'wb') as f:
            f.write(r.content)
        
    save_xl(r)