Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask: Get database rows as dictionary

Tags:

python

flask

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()
like image 597
ankush981 Avatar asked Dec 08 '22 00:12

ankush981


2 Answers

Simply add the line

app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
like image 89
David Okwii Avatar answered Dec 18 '22 03:12

David Okwii


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()
like image 24
lazy1 Avatar answered Dec 18 '22 05:12

lazy1