5
from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'todoapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
cur = mysql.connection.cursor()

if __name__ == '__main__':
    app.run()

There is error which is displayed after executing program:

cur = mysql.connection.cursor()

AttributeError: 'NoneType' object has no attribute 'cursor'.

According to documentaction it should work. I use Ubuntu 16.04, I have installed MySQL and it works properly. Could anyone explain why it doesn't work?

6 Answers 6

2

The problem is in :

app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

Looking at flaskext.mysql source , that feature is not yet implemented .

And since flaskext.mysql is using pymysql , you can use DictCursor from pymysql.cursors

Example :

from flaskext.mysql import MySQL 
from flask import Flask 
from pymysql import cursors

app=Flask(__name__)

mysql = MySQL(cursorclass=cursors.DictCursor)
mysql.init_app(app)
cursor = mysql.connect().cursor()
Sign up to request clarification or add additional context in comments.

3 Comments

I get the following error mysql = MySQL(cursorclass=cursors.DictCursor) TypeError: MySQL.__init__() got an unexpected keyword argument 'cursorclass'
@SuramuthuR , it maybe related to the version you are using , read the docs of that specific version .
Thanks for responding. After some search, I could get a module named mysql-connector-python and I got my problem resolved. I've explained in an answer to the same question.
2

You are constructing cursor based on flask_mysqldb , and Flask app won't be constructed itself up until the first route is hit, which means the Flask app will be constructed inside a Flask Function, and that is when your MySQL connection also can be constructed based on your app.config params, and then your cursor can be constructed based on MySQL connection: Flask Construction > MySQL Connection Construction > Cursor Construction.

So you have to use your cursor constructor inside a Flask Function: Instead of:

cur = mysql.connection.cursor()

Put:

@app.route("/")
def index():
   cur = mysql.connection.cursor()

1 Comment

Thanks for this - makes sense. Also why it wouldn't work from terminal!
1

I used the connect() method instead of get_db() and it works with Python 3.5.5. I had the same error when I used get_db

from flask import Flask
from flaskext.mysql import MySQL


app = Flask(__name__)


app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'test_db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql = MySQL()
mysql.init_app(app)

# cursor = mysql.get_db().cursor()
cursor = mysql.connect().cursor()
print(cursor)

Comments

1
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = 3308 #here your port

enter image description here

3 Comments

apparently by default the port is 3306, but you must put yours
To make this answer more useful to readers of this question, consider adding a description to explain what you're doing.
Please add some explanation to your answer such that others can learn from it
0

Today I had this problem and I was searching for the solution. As none of the answers here solved my problem, I got it solved with the module mysql-connector-python.

Install mysql-connector-python

pip3 install mysql-connector-python

Flask File:

from flask import Flask, request, jsonify
from mysql.connector import connect

app = Flask(__name__)

# Replace with your own database credentials
config = {
    "user": "username",
    "password": "password",
    "host": "localhost",
    "database": "database_name",
}

connection = connect(**config)

@app.route('/check_connection', methods=['GET'])
def check_connection():
    try:
        cursor = connection.cursor(dictionary=True)
        cursor.execute("SELECT VERSION()")
        data = cursor.fetchone()
        cursor.close()
        return jsonify({'status': 'success', 'version': data})
    except Exception as e:
        return jsonify({'status': 'failed', 'error': str(e)})
        
if __name__ == '__main__': app.run(debug=True)

Use your mysql queries as follows:

cursor.execute("<Your Mysql Query>")

Comments

-1

It maybe that you need to init the app for MySQL context.

from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)
mysql = MySQL()
mysql.config['MYSQL_HOST'] = 'localhost'
mysql.config['MYSQL_USER'] = 'root'
mysql.config['MYSQL_PASSWORD'] = 'password'
mysql.config['MYSQL_DB'] = 'todoapp'
mysql.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql.init_app(app)
cur = mysql.connection.cursor()

if __name__ == '__main__':
    app.run()

1 Comment

try with this? @Raken it might have to do with how the object is made using the extension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.