3

I have two servers where one is trying to get a file from the other. I am using Flask get requests to send simple data back and forth (strings, lists, JSON objects, etc.).

I also know how to send just a file, but I need to send an error code with my data.

I'm using something along the following lines:

Server 1:

req = requests.post('https://www.otherserver.com/_download_file', data = {'filename':filename})

Server 2:

@app.route('/_download_file', methods = ['POST'])
def download_file():
    filename = requests.form.get('filename')

    file_data = codecs.open(filename, 'rb').read()
    return file_data

Server 1:

with codecs.open('new_file.xyz', 'w') as f:
    f.write(req.content)

...all of which works fine. However, I want to send an error code variable along with file_data so that Server 1 knows the status (and not the HTTP status, but an internal status code).

Any help is appreciated.

2
  • Is there any special reason why HTTP error codes don't fill your need? Commented Aug 16, 2017 at 20:50
  • There are, but more importantly, I may also want to send information that is not an error code, but just additional data. Commented Aug 16, 2017 at 20:54

1 Answer 1

13

One solution that comes to my mind is to use a custom HTTP header.

Here is an example server and client implementation.

Of course, you are free to change the name and the value of the custom header as you need.

server

from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    response = send_from_directory(directory='your-directory', filename='your-file-name')
    response.headers['my-custom-header'] = 'my-custom-status-0'
    return response

if __name__ == '__main__':
    app.run(debug=True)

client

import requests

r = requests.post(url)

status = r.headers['my-custom-header']

# do what you want with status

UPDATE

Here is another version of the server based on your implementation

import codecs

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    filename = request.form.get('filename')

    file_data = codecs.open(filename, 'rb').read()
    response = make_response()
    response.headers['my-custom-header'] = 'my-custom-status-0'
    response.data = file_data
    return response

if __name__ == '__main__':
    app.run(debug=True)
Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to implement this into my live code right now. Either way, this is very helpful. Thank you
good to see it helped you. I edited the answer to include another implementation based on yours.

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.