AttributeError when initializing Flask app - 'MySQL' object has no attribute 'connection' - python

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?

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

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.

Related

Setting Up Flask DB2 connection

I am trying to connect my flask application to a DB2 database,but somehow I am unable to do. here is what I am trying to do,
I am using flask extension flask_db2 for this purpose and below is how I am trying to connect
from flask import Flask
from flask_db2 import DB2
app = Flask(__name__)
#app.route('/')
def index()
cur = db.connection.cursor("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;PWD=password)
from flask import Flask
from flask_db2 import DB2
app = Flask(__name__)
app.config['DB2_DATABASE'] = 'sample'
app.config['DB2_HOSTNAME'] = 'localhost'
app.config['DB2_PORT'] = 50000
app.config['DB2_PROTOCOL'] = 'TCPIP'
app.config['DB2_USER'] = 'db2inst1'
app.config['DB2_PASSWORD'] = 'db2inst1'
db = DB2(app) #You forgot that
#app.route('/')
def index():
cur = db.connection.cursor()
cur.execute(...)
First: You forgot to have an object to use the flask db2 module.
The DB2(app) is a constructor for your Flask extension and will bind your application to this module.
where as
db = DB2(app)
Initialises your db object with help of your extension's constructor which you can further use for your Database operations.
Secondly: use app configs to play with DB2 credentials. (This step should be done before you bind the app)
Third: You can execute your query like this
cur.execute("SELECT id FROM users") #something like that
I hope I have clarified :D just drop message. Ill try helping more.

Python/Flask mysql cursor: Why it doesn't work?

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?
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()
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)
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()
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = 3308 #here your port
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()

Flask flaskext.mysql no attribute connection

I'm trying to establish a connection to an sql database, but I end up with
AttributeError: 'MySQL' object has no attribute 'connection'
I've read through the documentation, and it looks like this is the proper way to create a cursor:
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'sql3.freemysqlhosting.net'
app.config['MYSQL_USER'] = 'sql1234567'
app.config['MYSQL_PASSWORD'] = 'abcdefg'
app.config['MYSQL_DB'] = 'sql1234567'
app.config['MYSQL_PORT'] = '3306'
mysql = MySQL(app)
#app.route('/')
def index():
cur = mysql.connection.cursor()
cur.execute('''SELECT * FROM users''')
rv = cur.fetchall()
return str(rv)
if __name__ == '__main__':
app.run(debug=True)
Edit: using https://www.youtube.com/watch?v=nWO_VpI5wn8 as a tutorial and the docs are http://flask-mysqldb.readthedocs.io/en/latest/
You are importing incorrect module here.
Solution is
Instead of importing
from flaskext.mysql import MySQL
import this which is different module (Follow this)
from flask_mysqldb import MySQL
This looks like an auto import issue from some IDE. As these two modules are different, you can install these two packages as following:
pip install flask-mysqldb and
pip install flask-mysql
EDIT
If you want to use the previous module, you will have to follow this and the cursor can be used as following:
from flaskext.mysql import MySQL
mysql = MySQL()
mysql.init_app(app)
cursor = mysql.get_db().cursor()

MySQL 5.7 and connection attribute

I have looked everywhere and well researched into different solutions. I have come closer to the solution by reducing the number of errors. Here is my piece of code that's giving me a headache
from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash,check_password_hash
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'BucketList'
mysql.init_app(app)
cur = mysql.connection.cursor()
I have been running the app.py file and keep getting the following error:
AttributeError: 'MySQL' object has no attribute 'connection'.
I am using MySQL 5.7 and attempting to create my first web app using a tutorial that's dated back in time. The above piece of code is after editing it closer to relevant standards.
The part of your code in which you instantiate the MySQl() object is incorrect. Instead of:
mysql = MySQL()
app = Flask(__name__)
It should be
app = Flask(__name__)
mysql = MySQL(app)

Flask-MySQL gives "closing a closed connection" error the second time a view runs

I am using Flask-MySQL to connect to my database in a view. The view works the first time I go to it, but when I go to it the second time it always crashes with the error:
ProgrammingError: closing a closed connection
Why am I getting this error? How do I connect successfully the second time?
from flask import Flask, render_template, request
from flaskext.mysql import MySQL
app = Flask(__name__)
#app.route('/hello/', methods=['POST'])
def hello():
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxx'
app.config['MYSQL_DATABASE_DB'] = 'pies'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
query = request.form['yourname']
mysql = MySQL(app)
conn = mysql.connect()
with conn as cursor:
try:
cursor.execute(query)
name = str(cursor.fetchone())
except:
name = "SQL is wrong"
conn.close()
return render_template('form_action.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
You should not be initializing the extension during every request. Create it during app setup, then use it during the requests. Setting configuration should also be done during app setup.
The extension adds a teardown function that executes after every request and closes the connection, which is stored as a threadlocal. Since on the second request you've registered the extension multiple times, it is trying to close the connection multiple times.
There's no need to call connect, the extension adds a before request function that does that. Use get_db to get the connection for the request. Since the extension closes this connection for you, don't call close either.
from flask import Flask
from flaskext.mysql import MySQL
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = 'xxx'
MYSQL_DATABASE_DB = 'pies'
MYSQL_DATABASE_HOST = 'localhost'
app = Flask(__name__)
app.config.from_object(__name__)
mysql = MySQL(app)
#app.route('/hello/')
def hello():
conn = mysql.get_db()
# ...
Note that Flask-MySQL is using a very old extension pattern that is no longer supported by Flask. It also depends on an unsupported mysql package that does not support Python 3. Consider using Flask-MySQLdb instead.

Categories