I'm building an application using Flask MySQLDb and wondering how to return database rows as dictionaries (like PHP's FETCH_ASSOC). The default fetchall()
method of the cursor class returns a tuple, and there's nothing about returning a dict in the docs of the underlying library.
So far I've been executing code the following format, but getting a dict with column names as keys would really help:
g.cursor.execute('SELECT email, password FROM users WHERE email = %s', [request.form['email']])
row = g.cursor.fetchall()
Simply add the line
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
You can use cursorclass
argument in the connect method and specify DictCursor when you create the cursor.
See here for example. In a nutshell:
import MySQLdb
from MySQLdb.cursors import DictCursor
conn = MySQLdb.connect(cursorclass=DictCursor)
g.cursor = conn.cursor()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With