lundi 2 mars 2020

Global variables alternatives in python flask (ajax request)

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 use in a situation like this?




Aucun commentaire:

Enregistrer un commentaire