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

标签 python mysql rest flask flask-restful

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

这是我的验证 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})

下面是 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 会隐式将其计算为 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 获取您的值(value)

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

关于python - 使用另一个 WS 作为验证 Flask/Rest/Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336439/

相关文章:

python - 在 Spyder 的编辑器中切换脚本的快捷方式

python - python中根据非连续整数、字符和 float 分割字符串

mysql - 实现动态更新upvote/downvote

python - 向 oanda 发送订单

c# - 获取 0 的 HttpStatusCode

java - RESTful 服务的时间戳精度问题

python - 根据条件将一系列函数应用于字符串的优雅方式

python - 在32位python解释器中导入64位dll时出现ImportError

mysql - 在 ListView 中应用多个过滤器

python - 如何使用 mysql 表中的信息创建条形图?