Search code examples
pythonflaskpymysql

Fetching values as {"property-name": "value"} using pymysql


I'm new to Python and I'm building a simple CRUD app using Flask. Here's how I'm doing it:

from flask import Flask,request
import pymysql.cursors

connection = pymysql.connect(
host='localhost',
db='mydb',
user='root',
password='password',
cursorclass='pymysql.cursors.DictCursor
)

@app.route('/login',methods=['POST'])
def login():
    cursor = connection.cursor(pymysql.cursors.DictCursor)
    cursor.execute("SELECT id,hash,displayName,attempt,status FROM users WHERE id=%s", (request.form['username']))
    user = cursor.fetchone()
    pprint(user)

But this code outputs something like this thing:

{u'displayName': 'John Smith',
 u'hash': 'somehash.asdf!@@#$',
 u'id': 'developer',
 u'attempt': 0,
 u'status': 1
}

The thing is, I can't seem to get these attributes using the standard user.hash syntax. Am I doing something wrong? I need to either:

  • convert it to JSON-like structure
  • get the properties of user when it's presented in this form

Solution

  • When using a pymysql.cursors.DictCursor cursor the fetched data is returned as a dictionary, therefore you can use all the common dict traversal/accessing/modifying methods on it.

    This means that you can access your returned hash as: user["hash"].

    When it comes to JSON, Python comes with a built-in json module that can readily convert your retrieved dict into a JSON string, so in your case, to get a JSON representation of the returned user dictionary use:

    import json
    
    json_string = json.dumps(user)
    print(json_string)  # or do whatever you need with it