使用另一个 WS 作为验证 Flask/Rest/Mysql

using another WS as validation Flask/Rest/Mysql

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

这是我的验证 WS,应该 return 一个 true/false。

@app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
def checkStudOnCourseWS(AppCode, ideal):

myCursor3 = mydb.cursor()
query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
myCursor3.execute(query3)
myresult3 = myCursor3.fetchall()

if len(myresult3) == 0:
    return render_template('Invalid.html')
else:
    return jsonify({'Student in course ': True})

下面是 regResult,它应该 SQL 插入到数据库中。如果上面的结果是 "True",我只希望提交工作,我该怎么做?我知道我没有执行 INSERT 查询,但这不是问题。 我不确定的是:如果验证 WS 是 "True",我怎样才能让提交被插入。

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


if request.method == "POST":

    Period = request.form['period']
    #ProvNr = request.form['provNr']
    Grade = request.form['grade']
    Applicationcode = request.form['applicationcode']
    #Datum = request.form['datum']
    Ideal = request.form['ideal']

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

起初,这样的语法:

if len(myresult3) == 0 可以简化为 if myresult3,因为 Python 将其隐式计算为布尔值。

其次,如果您从函数中返回一次,则无需编写else语句:

    if len(myresult3) == 0:
        return render_template('Invalid.html')  #  < -- in case 'True',
                                                #  it returns here, otherwise 
                                                #  function keeps going"""

     return jsonify({'Student in course ': True})  # < -- in case 'False', it is returned here

关注你的问题,你可以这样做:

从 ws 获取你的价值

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

从中提取json:

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

做一些检查:

if result_as_json.get('Student in course', False):  #  I highly suggest to use other 
                                                   #  convention to name json keys 
                                                   #  e.g. Student in course -> 
                                                   #  student_exists_in_course
    #  do your code here