使用另一个ws作为验证 flask /rest/mysql

ou6hu8tu  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(449)

我正在尝试用3个web服务构建一个简单的web应用程序。我的两个web服务应该验证一个学生是否存在于课程中。这是通过一个简单的select查询完成的。我的第三个web服务应该将一个学生添加到数据库中,但前提是该学生确实存在于特定的课程中。
这是我的验证ws,它应该返回true/false。

  1. @app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
  2. def checkStudOnCourseWS(AppCode, ideal):
  3. myCursor3 = mydb.cursor()
  4. query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
  5. myCursor3.execute(query3)
  6. myresult3 = myCursor3.fetchall()
  7. if len(myresult3) == 0:
  8. return render_template('Invalid.html')
  9. else:
  10. return jsonify({'Student in course ': True})

下面是应该向数据库中插入sql的regresult。我只想提交工作,如果上述结果是“真的”,我怎么做呢?我知道我还没有完成insert查询,但这不是问题。我不确定的是:如果validation ws为“true”,我如何才能让submit被插入。

  1. @app.route('/register', methods=["POST", "GET"])
  2. def regResultat():
  3. if request.method == "POST":
  4. Period = request.form['period']
  5. #ProvNr = request.form['provNr']
  6. Grade = request.form['grade']
  7. Applicationcode = request.form['applicationcode']
  8. #Datum = request.form['datum']
  9. Ideal = request.form['ideal']
  10. CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
  11. CheckStudOnResp = requests.get(CheckStudOnCourse)
sr4lhrrt

sr4lhrrt1#

首先,这样的语法: if len(myresult3) == 0 ,可以简化为 if myresult3 ,因为python隐式地将其计算为bool。
其次,如果从函数返回,则无需编写else语句:

  1. if len(myresult3) == 0:
  2. return render_template('Invalid.html') # < -- in case 'True',
  3. # it returns here, otherwise
  4. # function keeps going"""
  5. return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here

专注于你的问题,你可以这样做:
从ws获得您的价值

  1. CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
  2. CheckStudOnResp = requests.get(CheckStudOnCourse)

从中提取json:

  1. if result_as_json.status == 200:
  2. result_as_json = CheckStudOnResp.json() # < -- it is now a dict

做一些检查:

  1. if result_as_json.get('Student in course', False): # I highly suggest to use other
  2. # convention to name json keys
  3. # e.g. Student in course ->
  4. # student_exists_in_course
  5. # do your code here
展开查看全部

相关问题