Home > Software engineering >  How to access a variable declared inside IF statement outside IF statement in Python
How to access a variable declared inside IF statement outside IF statement in Python

Time:11-16

I'm trying to use searchData outside my if statement so I could use the variable inside my query. but it gives me an error of UnboundLocalError: local variable 'searchData' referenced before assignment

@app.route('/ML', methods=['GET', 'POST'])
def index():
  if request.method == "POST":
        request_data = json.loads(request.data)
        searchData = (request_data['content'])
        return jsonify(searchData)
  mycursor = mydb.cursor(dictionary=True)
  query = "SELECT * FROM COMPANY WHERE COMPANY_NAME LIKE %s LIMIT 20;"
  mycursor.execute(query,("%"   searchData   "%",))
  myresult = mycursor.fetchall()

  company = []
  content = {}

  for result in myresult:
     content ={'COMPANY_NAME':result['COMPANY_NAME'],}
     company.append(content)
     content = {}
  return jsonify(company)

I've also tried declaring searchData just above my if statement. it removes the error but the value isn't changed by my if statement. It stays just how I declared it. I appreciate any help anyone could give. Thank you in advance.

CodePudding user response:

It seems that this problem can be alleviated by the global treatment to the variable. How about declaring the searchData as global first?

@app.route('/ML', methods=['GET', 'POST'])
def index():
  global searchData
  if request.method == "POST":
        request_data = json.loads(request.data)
        searchData = (request_data['content'])
        return jsonify(searchData)
  mycursor = mydb.cursor(dictionary=True)
  query = "SELECT * FROM COMPANY WHERE COMPANY_NAME LIKE %s LIMIT 20;"
  mycursor.execute(query,("%"   searchData   "%",))
  myresult = mycursor.fetchall()

  company = []
  content = {}

  for result in myresult:
     content ={'COMPANY_NAME':result['COMPANY_NAME'],}
     company.append(content)
     content = {}
  return jsonify(company)

CodePudding user response:

You have a return searchedInput statement in if statement block, removing it may solve your problem. return statement will terminates your function execution.

For GET method, searchedInput should declared before if statement.

  • Related