Python Flask: Send file and variable

前端 未结 1 1762
情书的邮戳
情书的邮戳 2021-01-23 05:51

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.).

相关标签:
1条回答
  • 2021-01-23 06:43

    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)
    
    0 讨论(0)
提交回复
热议问题