0

I'm now using ajax to send a request to the server (flask). However, I want to use the object created in the home method but It seems that I can't directly access the object without the use of global variable.

Problem:

@app.route('/ajax_request',methods = ['POST', 'GET'])
def ajax_request():
  #I want to use the object that initializes in "home" method

@app.route('/home',methods = ['POST', 'GET'])
def home():
  user = request.form["name"]

  #object created based on "user" variable obtained from the URL routing request
  obj = Class(user)

  return render_template("home.html")

Using global variable:

global_obj = None

@app.route('/ajax_request',methods = ['POST', 'GET'])
def ajax_request():

  print(global_obj)
  #use global_obj to do something

@app.route('/home',methods = ['POST', 'GET'])
def home():
  user = request.form["name"]

  global global_obj
  global_obj = Class(user)

  return render_template("home.html"

I have read many posts and articles mentioned that using global variables is a bad programming practice. Hence, is there any alternatives can be used in a situation like this?

Kyle_397
  • 439
  • 4
  • 14
  • 1
    You should be careful with inter-API states. **Stateless** server is best for maintaining, but if you still need contexts, Flask provides its own global context. Or you can use Database like Redis. – Boseong Choi Mar 02 '20 at 10:35
  • Just curios.. why you want to use the same object? why can't this object created again and again? – anuragal Mar 02 '20 at 10:37
  • You should make use of tokens. Once you login a user, generate and return a token. Make further requests using that token – Ejaz Mar 02 '20 at 10:57
  • You can follow this article - https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask – Ejaz Mar 02 '20 at 11:01
  • @BoseongChoi Yes, but what I want to implement is to store data temporarily in the application (front end) before deploying to the database (back-end). Flask indeed has its own global context, but I don't think that it is suitable to be used in a situation like this. – Kyle_397 Mar 02 '20 at 11:29
  • @anuragal Notice in first code that the object is created (`obj = Class(user)`) based on a POST/GET request (`user = request.form["name"]`). In the ajax request method, I want to access/use the object created in the **home** method. – Kyle_397 Mar 02 '20 at 11:37
  • @Ejaz Yes, tokens is indeed the optimal approach for login. How about data other than user? like books, shapes etc – Kyle_397 Mar 02 '20 at 11:41
  • If you are talking about keeping data in the client-side, then you can read about localstorage. – Ejaz Mar 02 '20 at 11:50

0 Answers0