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

2024-06-17 11:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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)

Tags: formweb数据库appstringwsrequestselect
1条回答
网友
1楼 · 发布于 2024-06-17 11:59:51

首先,这样的语法:

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

相关问题 更多 >