You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask API实现MySQL用户CRUD:创建用户接口报TypeError问题

Flask + MySQL 创建用户接口 TypeError 问题解决

问题描述

我正在学习使用Flask API结合MySQL数据库实现基础用户CRUD操作,查询所有用户功能运行正常,但创建用户接口却抛出TypeError。

我的创建用户端点代码(使用flask-mysqldb):

@app.route('/create', methods=['POST'])
def create_user():
    try:
        if not request.is_json:
            return jsonify({"message": "Bad Request: Request body must be JSON ☠️ "}), 400
        else:
            data = request.get_json()
            
            fname = data.get('first_name')
            lname = data.get('last_name')
            gender = data.get('gender')
            email = data.get('email')
            phone = data.get('phone')
            country_code = data.get('country_code')
            
            
            if fname and lname and email and gender and phone and country_code:
                conn = mysql.connect()
                cur = conn.cursor()


                cur.execute("""INSERT INTO users (fname, lname, gender, email, phone_number, phone_country_code) VALUES (%s,%s,%c,%s,%s,%s) """.format(fname, lname, gender, email, phone_number, country_code))
                conn.commit()
          
                
                cur.close()
                conn.close()
                return jsonify({"message": "User created successfully 🥳 "}), 200
            else:
                return jsonify({"message": "Some data is missing 🙁 "}), 200
    except Exception as e:
        print(e)

通过Postman传递的JSON数据(已确认能进入if判断):

{
    "first_name" : "John",
    "last_name" : "Doe",
    "gender" : "M",
    "email" : "john@fakedoe.com",
    "phone" : "9876543210",
    "country_code" : "UK"
}

错误原因分析

  1. MySQL占位符使用错误:SQL语句中用了%c作为gender的占位符,但MySQL的参数占位符统一使用%s(不管字段是字符还是其他类型),%c会导致格式解析错误。
  2. 变量名不匹配:代码中引用了phone_number,但实际定义的变量是phone,未定义的变量会触发TypeError。
  3. 错误的SQL参数传递方式:用.format()直接拼接SQL参数是错误的,既会引发字符串格式化错误,还存在SQL注入风险,正确的做法是把参数作为execute()方法的第二个参数传入。

修正后的代码

@app.route('/create', methods=['POST'])
def create_user():
    try:
        if not request.is_json:
            return jsonify({"message": "Bad Request: Request body must be JSON ☠️ "}), 400
        
        data = request.get_json()
        
        fname = data.get('first_name')
        lname = data.get('last_name')
        gender = data.get('gender')
        email = data.get('email')
        phone = data.get('phone')
        country_code = data.get('country_code')
        
        if fname and lname and email and gender and phone and country_code:
            conn = mysql.connect()
            cur = conn.cursor()
            
            # 修正:占位符统一用%s,参数作为execute第二个参数传入
            cur.execute("""
                INSERT INTO users (fname, lname, gender, email, phone_number, phone_country_code) 
                VALUES (%s, %s, %s, %s, %s, %s)
            """, (fname, lname, gender, email, phone, country_code))
            conn.commit()
            
            cur.close()
            conn.close()
            return jsonify({"message": "User created successfully 🥳 "}), 201
        else:
            return jsonify({"message": "Some data is missing 🙁 "}), 400
    except Exception as e:
        print(e)
        return jsonify({"message": f"Error creating user: {str(e)}"}), 500

额外优化点

  • 创建成功的状态码改为符合REST规范的201(资源已创建)
  • 缺失参数的状态码改为400(请求错误)
  • 异常捕获后返回错误信息给客户端,方便调试

内容的提问来源于stack exchange,提问作者Rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:01:18