使用 pymysql 获取值作为 {"property-name": "value"}
Fetching values as {"property-name": "value"} using pymysql
我是 Python 的新手,我正在使用 Flask 构建一个简单的 CRUD 应用程序。我是这样做的:
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)
但是这段代码输出的是这样的东西:
{u'displayName': 'John Smith',
u'hash': 'somehash.asdf!@@#$',
u'id': 'developer',
u'attempt': 0,
u'status': 1
}
问题是,我似乎无法使用标准 user.hash
语法获取这些属性。难道我做错了什么?我需要:
- 将其转换为 JSON 类结构
- 获取
user
以这种形式呈现时的属性
在其上使用 pymysql.cursors.DictCursor
cursor the fetched data is returned as a dictionary, therefore you can use all the common dict
traversal/accessing/modifying 方法时。
这意味着您可以访问返回的 hash 作为:user["hash"]
.
当谈到 JSON 时,Python 附带了一个 built-in json
模块,可以轻松地将检索到的 dict
转换为 JSON 字符串,因此在您的情况下,要获得返回的 user
字典的 JSON 表示,请使用:
import json
json_string = json.dumps(user)
print(json_string) # or do whatever you need with it
我是 Python 的新手,我正在使用 Flask 构建一个简单的 CRUD 应用程序。我是这样做的:
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)
但是这段代码输出的是这样的东西:
{u'displayName': 'John Smith',
u'hash': 'somehash.asdf!@@#$',
u'id': 'developer',
u'attempt': 0,
u'status': 1
}
问题是,我似乎无法使用标准 user.hash
语法获取这些属性。难道我做错了什么?我需要:
- 将其转换为 JSON 类结构
- 获取
user
以这种形式呈现时的属性
在其上使用 pymysql.cursors.DictCursor
cursor the fetched data is returned as a dictionary, therefore you can use all the common dict
traversal/accessing/modifying 方法时。
这意味着您可以访问返回的 hash 作为:user["hash"]
.
当谈到 JSON 时,Python 附带了一个 built-in json
模块,可以轻松地将检索到的 dict
转换为 JSON 字符串,因此在您的情况下,要获得返回的 user
字典的 JSON 表示,请使用:
import json
json_string = json.dumps(user)
print(json_string) # or do whatever you need with it