mysql - 'NoneType' 对象没有属性 'cursor'

标签 mysql flask mysql-python

我使用 Flask 创建了一个非常简单的 Web 应用程序,并且连接了一个 MySQL 数据库。仅供引用,我在 Windows 上使用 bash。

下面的函数将一个人注册到 Mysql 数据库中,它按预期工作。定义游标对象并将数据保存到MySQL。

@app.route('/register', methods=['GET','POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        name = form.name.data
        email = form.email.data
        username = form.username.data
        password = hash.encrypt(str(form.password.data))

        # Create cursor
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users(name, email, username, password) VALUES(%s, %s, %s, %s)",
        [name, email, username, password])

        # commit to db
        mysql.connection.commit()

        # close connection
        cur.close()

        flash('You are now registered and can log in', 'success')

        return redirect(url_for('login'))

    return render_template('register.html', form=form)

当我想从 mysql 加载数据时,问题就开始了:

def data():
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users")
    mysql.connection.commit()
    cur.close()

data()

我得到错误:

File "app.py", line 23, in data cur = mysql.connection.cursor() AttributeError: 'NoneType' object has no attribute 'cursor'

正如@Martijn Pieters 所指出的,这意味着我无法连接到 mysql 数据库。问题是,为什么 flask 在第一个函数中连接没有问题,而在第二个函数中出现问题?

以下是我要复制的导入:

from flask import Flask, render_template, flash, request, redirect, url_for, session, logging, url_for
from data import Articles
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt

app = Flask(__name__)

#init MYSQL
mysql=MySQL(app)

最佳答案

错误发生是因为mysql.connectionNonemysql 是什么类型的对象在这里并不重要。

Flask-MySQL documentation for MySQL.connection告诉您该属性何时变为 None:

Attempts to connect to the MySQL server.

Returns: Bound MySQL connection object if successful or None if unsuccessful.

所以尝试连接到服务器可能会失败。该扩展将为每个请求打开一次与 MySQL 的连接;它无法根据成功请求的单独请求进行连接。

查看 source code for the extension我看到当没有应用上下文时它也会返回 None(此时 _app_ctx_stack.topNone)。您不能在请求之外使用此功能。

如果你在请求之外确实需要这个,你需要 manually create an app context第一:

with app.app_context():
    cur = mysql.connection.cursor()

关于mysql - 'NoneType' 对象没有属性 'cursor',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52779975/

相关文章:

mysql - 在 RAILS 中查询比通过 Mysql 客户端查询花费的时间更长

python - 在 OpenShift 中以 HTTPS 模式配置 python flask 应用程序

python - 用 Flask 重写 URL

MySql:选择每组的最大值以及相应的值id

mysql - 来自 MySQL 的 ActiveRecord/Rails 查询数据排序问题 - SQLite 中没有问题

python - 使用与 Amazon RDS 的 MySQLdb SSL 连接获取空 'Ssl_cipher'

python - Django DB优化过滤器点击ip和1小时差异

Python:如何将所有 'for loop' 输出作为一个变量解析到 mysql 更新查询

mysql - 另一个表中的最新相关条目

python - 浏览器不解释我的 CSS