0

I'm trying to run a flask app together with a MySQL server. But I can't seem to get pass the connect-to-db stage. My app.py has the following code:

from flask import Flask, render_template
from flaskext.mysql import MySQL

app = Flask(__name__)
mysql = MySQL()

app.config['MYSQL_DATABASE_HOST '] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypassword'
app.config['MYSQL_DATABASE_DB'] = 'users'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql.init_app(app)
cur = mysql.connection.cursor()

@app.route('/')
def index():
    return render_template('layout.html')

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

When I run this script in Git Bash, I get:

$ python app.py
Traceback (most recent call last):
  File "app.py", line 13, in <module>
    cur = mysql.connection.cursor()
AttributeError: 'MySQL' object has no attribute 'connection'

I do not see any issue with the app.py script above. The MySQL module is imported, initialized and it still does not run. Can someone please offer some suggestions of what could possibly be the problem?

1
  • Try this: from flask_mysqldb import MySQL instead of from flaskext.mysql import MySQL... Or use your previous import and use the cursos as: cur = mysql.get_db().cursor(). Commented Feb 18, 2018 at 18:46

2 Answers 2

1

I think you should import this and then run your code :

import mysql
import mysql.connector
Sign up to request clarification or add additional context in comments.

Comments

0

You can change the way you are getting the cursor to:

mysql.init_app(app)
cur = mysql.get_db().cursor()

Or use your previous code and change the import line to:

from flask_mysqldb import MySQL

I hope it helps.

Comments

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.