关于mysql:’NoneType’对象没有属性’cursor’

'NoneType' object has no attribute 'cursor'

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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加载数据时,问题就开始了:

1
2
3
4
5
6
7
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数据库。 问题是,为什么烧瓶连接第一功能时没有问题,而第二功能有问题?

以下是我要复制的导入:

1
2
3
4
5
6
7
8
9
10
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.connectionNone。 这里的对象mysql是什么类型都没有关系。

mysql.connection的Flask-MySQL文档告诉您该属性何时为None

Attempts to connect to the MySQL server.

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

因此,尝试连接到服务器可能会失败。 该扩展将为每个请求打开一次与MySQL的连接; 它无法成功连接到另一个请求。

查看扩展的源代码,我看到当没有应用程序上下文时,它也会返回None(此时_app_ctx_stack.topNone。您不能在请求之外使用此功能。)

如果确实在请求之外需要此功能,则需要先手动创建应用上下文:

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