如何使用 Flask Python API 取回基于参数输入的值

How to get back a value based by parameter input using Flask Python API

当我尝试卷曲它或直接转到 URL 时,我一直收到以下错误,即 127.0.0.1:5000/api/v1/currentuserid/3/ .. 看不出我的代码有什么问题:

TypeError: 'NoneType' 对象不可调用

@app.route('/api/v1/currentuserid/<userid>/', methods=['GET'])
def api_retrieve_useridd(userid):
    try:
        mycursor = mydb.cursor()
        _json = request.get_json()
        userid = _json('userid')
        
        if userid and request.method == 'GET':
            sqlQuery = "SELECT username FROM tblUser WHERE user_id=%s"
            bindData = (userid,)
            mycursor.execute(sqlQuery, bindData)
            row_headers=[x[0] for x in mycursor.description] #this will extract row headers
            rv = mycursor.fetchone()
            json_data=[]
            json_data.append(dict(zip(row_headers,rv)))
            return jsonify(json_data[0])
        else:
            return not_found()
    finally:
        mycursor.close()

userid 参数已通过您定义的 Flask 路由传递给函数。所以你不需要从 request.get_json() 中获取值。您可以尝试以下代码。顺便说一句,您可以通过在路由定义中执行 <int:userid>user_id 类型强制为 int

@app.route('/api/v1/currentuserid/<int:userid>/', methods=['GET'])
def api_retrieve_useridd(userid):
    try:
        mycursor = mydb.cursor()
        
        if userid and request.method == 'GET':
            sqlQuery = "SELECT username FROM tblUser WHERE user_id=%s"
            bindData = (userid,)
            mycursor.execute(sqlQuery, bindData)
            row_headers=[x[0] for x in mycursor.description] #this will extract row headers
            rv = mycursor.fetchone()
            json_data=[]
            json_data.append(dict(zip(row_headers,rv)))
            return jsonify(json_data[0])
        else:
            return not_found()
    finally:
        mycursor.close()