android pre-junior
android pre-junior

Reputation: 1

passing data to a global variable FLASK and using it

I make a request to transfer data via CURL to the POST method, where I set the global variable data to value, then I need to use the same variable in another method, but after the request the data disappears.

How to write data so that it does not disappear after a request?

POST request:

curl --request POST --header 'Content-Type: application/json' --data '{"K":10,"Sums":[1.01,2.02],"Muls":[1,4]}' 'http://127.0.0.1:5000/PostInputData'

GET request:

curl http://127.0.0.1:5000/GetAnswer

Program code:

from flask import Flask, jsonify, request, json, abort
import requests, json

app = Flask(__name__)

data = ''


def calculate(jsn):
    jsn_out = {
        'SumResult': 0,
        'MulResult': 1,
        'SortedInputs': []
    }
    k = jsn['K']
    sum = 0
    for el in jsn['Sums']:
        sum += el
        jsn_out['SortedInputs'].append(el)

    jsn_out['SumResult'] = round(sum * k, 2)

    for el in jsn['Muls']:
        jsn_out['MulResult'] *= el
        jsn_out['SortedInputs'].append(el)

    jsn_out['SortedInputs'].sort()
    return jsn_out


@app.route('/')
def index():
    return ''


@app.route('/Ping')
def ping():
    res = requests.get('http://127.0.0.1:5000/')
    if res.status_code == 200:
        return jsonify(res.status_code)
    else:
        return abort(400)


@app.route('/PostInputData', methods=['POST'])
def post_input_data():
    data = request.get_json(force=True)
    print(data)
    # data is empty
    return jsonify(data)


@app.route('/GetAnswer')
def get_answer():
    print(data)
    return jsonify(data)


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

Upvotes: 0

Views: 840

Answers (1)

Riley Pagett
Riley Pagett

Reputation: 373

Here's more info about the Flask request lifecycle if you're interested. You're exactly right that once Flask is done handling a request, the data is gone.

There is a global variable storage in Flask, but for this kind of data you're better off using a cache, in my opinion. Flask-Caching is one example of a package that can help you do that.

Upvotes: 1

Related Questions