简体   繁体   中英

GET and POST in same Flask method

@app.route('/predict', methods=['GET', 'POST'])
def predict1(): 
  # radio = 0
  if request.method == 'POST':
      value = request.get_json()

      if(value['radioValue'] == 'word'):         
          radio = 0
          return "ok"
      elif(value['radioValue'] == 'sentence'):  
          radio = 1  
          return "ok"    
  else:                                          
      if(radio==0):          
          lists = ["my","word"]
      elif(radio==1):   
          lists = ["my","sentence"]
    
      return jsonify({'prediction': lists})

Hello, I am new to Flask and web development. So, here is my question, I am getting two radio button value named word and sentence. I want to pass lists = ["my","word"] if value is word else lists = ["my","sentence"] .

But here jsonify() is not returning anything. So what am I doing wrong here? Though it return lists if I declare radio variable outside if-else block as you can see I commented them out. Also if I don't return anything inside post what I did as return "ok" it doesn't return anything even if I declare radio = 0 or 1 outside if-else block. A short explanation will be really helpful.

If you check your debug log, you will probably see a NameError where radio is not defined. This is due to radio being a local variable, and not a session variable as you probably intended.

To store variables for further usage in Flask, you need to use sessions .

from flask import session

@app.route('/predict', methods=['GET', 'POST'])
def predict1(): 
  if request.method == 'POST':
      value = request.get_json()
      if(value['radioValue'] == 'word'):         
          session["radio"] = 0
          return "ok"
      elif(value['radioValue'] == 'sentence'):  
          session["radio"] = 1  
          return "ok"    
  else:                                          
      if(session["radio"]==0):          
          lists = ["my","word"]
      elif(session["radio"]==1):   
          lists = ["my","sentence"]
    
      return jsonify({'prediction': lists})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM