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

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

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

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

@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)
sr4lhrrt

sr4lhrrt1#

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

相关问题