Python Flask API Restful

标签 python mysql api

你好吗?我正在玩,用Python+Flask+MySQL来创建一个API。但我有一些错误!随着连接。这是入口点的代码。

@app.route('/add', methods=['POST'])
def add_user():
    try:
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _password = _json['pwd']
        # validate the received values
        if _name and _email and _password and request.method == 'POST':
            #do not save password as a plain text
            _hashed_password = generate_password_hash(_password)
            # save edits
            sql = "INSERT INTO user(user_name, user_email, user_password) VALUES(%s, %s, %s)"
            data = (_name, _email, _hashed_password,)
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(sql, data)
            conn.commit()
            resp = jsonify('User added successfully!')
            resp.status_code = 200
            return resp
        else:
            return not_found()
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

enter image description here

这里是错误

enter image description here

我已经安装了所有依赖项,但是......我不知道。我以前连接过光标,但没有连接。

你能帮我吗?谢谢!

最佳答案

在 try 子句中定义并在 finally 子句中使用的游标变量。您可能会在定义游标之前遇到异常(我假设当您尝试创建到 mysql 的连接时),因此您会收到此错误。

关于Python Flask API Restful,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54769603/

相关文章:

python - 如何重置从 ipywidget 命令按钮生成的输出,以便仅显示更新的 DataFrame?

python - double 到 PyFloat 转换不正确

php - 调用未定义函数 mysqli_connect() 问题

mysql - 为什么 COUNT 匹配两个 JOIN 值,但只指定了一个特定值

api - 是否可以通过 url 搜索 Twitter 用户?

python - PyQtGraph : how to change size (height and width) of graph in a ScrollArea

python - Raspberry Pi 湿度传感器未定义引用 'pinMode' 等

php - 如何让多个开源网络应用程序使用同一个数据库

api - 如何包含对 raml 资源的常见响应

php - 连接失败 : 0 push notification