Nanditha
Nanditha

Reputation: 53

TypeError: cursor() got an unexpected keyword argument 'dictionary' using flaskext.mysql

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

Answers (1)

arshovon
arshovon

Reputation: 13661

You can follow this answer: https://stackoverflow.com/a/41388992/3129414

Existing code modification:

  • use DictCursor in MySQL initialization
  • remove dictionary=True from cursor
  • use json package to convert dictionary items to json format

app.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:

dictionary output using flaskext

Upvotes: 3

Related Questions