Reputation: 53
I'm using flask framework and MySQL database connector.
I did the below:
from flaskext.mysql import MySQL
mysql = MySQL()
## app.config database configuration code
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor();
cursor.execute(
'SELECT * FROM customer WHERE email = (%s)', (username,)
)
user = cursor.fetchone()
I can access the user columns using index like user[8]
(which I need to execute the query once and check the column number), but when I try to specify
conn = mysql.connect(dictionary=True)
I get the error
'TypeError: cursor() got an unexpected keyword argument 'dictionary''
Is there a way to get the results of the query in dictionary format when using flask-MySQL?
Upvotes: 1
Views: 7491
Reputation: 13661
You can follow this answer: https://stackoverflow.com/a/41388992/3129414
Existing code modification:
DictCursor
in MySQL
initializationdictionary=True
from cursorjson
package to convert dictionary items to json formatapp.py
:
import json
from flask import Flask
from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '123'
app.config['MYSQL_DATABASE_DB'] = 'practice_db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql = MySQL(cursorclass=DictCursor)
mysql.init_app(app)
conn = mysql.connect()
@app.route("/", methods=['GET'])
def home():
email_address = '[email protected]'
cursor = conn.cursor();
cursor.execute(
'SELECT * FROM user_table WHERE email = (%s)', (email_address,)
)
users = cursor.fetchall()
return json.dumps(users)
app.run(debug=True)
Screenshot:
Upvotes: 3