Search code examples
pythonpandasdataframeflask

How to return DataFrame from flask view function and to another python request


Python 1 app is calling url to receive DataFrame.

ret = requests.post(url, json = myobj)

Another python 2 app flask view function is supposed to reurn Dataframe .

How to do because falsk function is not able to return Dataframe.


Solution

  • You can choose JSON as the format for the data.
    With pandas.DataFrame.to_json the data frame is converted to JSON and can then be sent.
    See also pandas.read_json to convert the JSON data back into a data frame.

    from flask import Flask
    import io 
    import pandas as pd
    import requests 
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        data = {
            'Name': ['Gerald','Ben','Charlotte'],
            'Age': [12, 25, 31],
        }
        df = pd.DataFrame(data, columns= ['Name', 'Age'])
        return app.response_class(
            df.to_json(orient='records'), 
            mimetype='application/json'
        )
    
    
    @app.route('/retrieve')
    def retrieve():
        r = requests.get(
            'http://127.0.0.1:5000/', 
            headers={'Accept': 'application/json'}
        )
        r.raise_for_status()
        df = pd.read_json(io.StringIO(r.text), orient='records')
        print(df)
        return ''