AssertionError on Flask connection to mysql (python)

27 Views Asked by At

When trying to reach localhost:5000/mysqltest the server throws the following exception :

AssertionError: The setup method 'teardown_request' can no longer be called on the application. It has already handled its first request, any changes will not be applied consistently. Make sure all imports, decorators, functions, etc. needed to set up the application are done before running it.

import os
from flask import Flask
from flaskext.mysql import MySQL

app=Flask(__name__)
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = 'mydbuser'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypassword'
app.config['MYSQL_DATABASE_DB'] = 'mydatabasename'


@app.route('/mysqltest')
def mysqlselect():
    mysql = MySQL(app)
    cnx = mysql.connect()
    cursor=cnx.cursor()
    cursor.execute(''' select tk_date from token ''')
    data=cursor.fetchall()
    print (data)
    cursor.close()
    return "test"


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

I expected the issue to come from a bad installation of the extension flask-mysql. I also double checked my dependencies.

1

There are 1 best solutions below

0
Slim KETARI On

Actually this was a very silly mistake : the line : mysql = MySQL(app)

shall not be in the function but in the beginning of the code as follows :

import os
from flask import Flask
from flaskext.mysql import MySQL

app=Flask(__name__)
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = 'mydbuser'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypassword'
app.config['MYSQL_DATABASE_DB'] = 'mydatabasename'
mysql = MySQL(app)

@app.route('/mysqltest')
def mysqlselect():
    cnx = mysql.connect()
    cursor=cnx.cursor()
    cursor.execute(''' select tk_date from token ''')
    data=cursor.fetchall()
    print (data)
    cursor.close()
    return "test"


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