1

I am going to set some data in a global variable once "/setvalue" route is called.

Then whoever wants to retrieve this data(even from outside of the web app, browser) can access it.

The problem is the call for retrieving the data comes from outside, e.g. a client who hits the URL from any browser can get this data

I have tried using "g" as follow, but it is not working:

from flask import g

@app.route("/setvalue", methods = ['POST'])
def setvalue():  
    content = request.get_json()
    g.content = content
    return format(content) #"set"


@app.route("/getvalue" )
def getvalue():      
    return g.content 


from flask import Flask, jsonify, request
from flask import g

As the above code show, I will call "/setvalue" to initiate the web app.

And whoever calls "/getvalue" will get the value that was initiated.

But g.content doesn't seem to work this way. I received a 500 error.

What is missing from my code? Thanks in advance. Your help would be greatly appreciated

  • `g` is for sharing stuff along the current request. I think it’s safe to just use a global? `nonlocal content` in `setvalue()` and `return content` in `getvalue()`. – Ry- Apr 01 '19 at 18:17

1 Answers1

0

I am not sure if this is the best way to handle this but a quick fix could be this.

You could try setting the variable to a default value first, then use the global keyword to access it inside your functions.

content = "Some default value"
def setvalue():
     global content
     content = request.get_json()

def getvalue():    
     global content  
     return content

Important note: this is not thread safe. You should either use an in-memory database or perhaps some locks.

EDIT: Based on this link I think this might actually be thread-safe in python. Although if you are using processes you still need a database.

Aristotelis V
  • 396
  • 1
  • 9
  • 2
    To say nothing of multi-processes (e.g. `app.run(processes=3)`) when there's no state shared between all workers. A proper database would help. – 9000 Apr 01 '19 at 18:31
  • Thanks, adding the global content works. Can you please show me an example on how I can set locks or use an in-memory db? Or how I can use app.run(process=3)? Thanks in advance. – user3033959 Apr 01 '19 at 19:39
  • 1
    Can you actually end up with a corrupted value like that in Python? – Ry- Apr 02 '19 at 08:19
  • @Ry- I am not a python expert but after some research I think you are right, you cannot end up with a corrupted value in Python. I've updated my answer. – Aristotelis V Apr 02 '19 at 09:54