Search code examples
pythonpostflaskget

Flask: store value with POST method and retrieve it with GET method


I've been working with Flask for quite a bit.

I have an output, just a number which increases or decreases constantly, I want to capture it with flask POST method and, retrieve immediately.

I've created an application to retrieve the latest POST in a GET method using the same context:

cumulative = ['x']
@app.route('/xxx', methods=['GET', 'POST'])
def refresh():
    aexample = request.get_json()
    cumulative.append(aexample)
    return str(cumulative[1]['thing2'])

It works, but if you refresh the page sometimes this error appears in the logs:

TypeError: 'NoneType' object is not subscriptable

In this line:

cumulative.append(aexample)

I've tried using:

cumulative[0] = aexample

But that doesn't work, it says the value is "None". That's why I made it incremental (just for test purposes).

All of this makes me think, storing the latest POST values in a list isn't the smart way to do this.

I've been thinking on using some sort of cache, the posted value changes every minute and I would like to retrieve only the latest posted value. I'm not interested in storing the values permanently.

Is there a good way to do this?


Solution

  • Ok, first thanks to @dylanj.nz for pointing my error with the requests.

    Finally I've achieved what I wanted, I've created conditionals for both requests, this is the code on flask:

    # 'Some Kind of Real Time Stuff'
    cumulative = ['x']
    @app.route('/xxx', methods=['GET', 'POST'])
    def refresh():
        aexample = request.get_json()
        if flask.request.method == 'POST':
            cumulative[0] = str(aexample)
            return 'data received'
        if flask.request.method == 'GET':
            return str(cumulative[0])
    

    [ Using CURL to send data ] Now, sending data to the method:

    curl -XPOST -H "Content-Type: application/json" http://someProject/xxx -d '{"thing2":"sdpofkdsofk"}'
    

    [ Apache - Log ]The POST were received successfully:

    myapacheserver:80 76.5.153.20 - - [23/Jul/2019:11:02:40 -0400] "POST /xxx HTTP/1.1" 200 182 "-" "curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3"
    

    [ Apache - Log ] GET works! presenting the latest value:

    myapacheserver:80 76.220.156.100 - - [23/Jul/2019:11:03:52 -0400] "GET /xxx HTTP/1.1" 200 327 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
    

    This is displayed on the page http://myapacheserver/xxx:

    {'thing2': 'sdpofkdsofk'}
    

    Yes, I'm storing the dict as an string, but it works, I'll deal later with the data type.