Python Flask REST API MySQL 获取游标键和值



我使用 Python3/Flask/MySQL 编写了一些测试代码,以使用 SELECT 查询从 MySQL 数据库获取响应。但是我无法根据值解析行名(键(。

import pymongo, json
import pymysql
from flask import Flask, request, jsonify
from flask_limiter import Limiter
from werkzeug.contrib.fixers import ProxyFix
from flask_restful import Resource, Api
from gevent.pywsgi import WSGIServer
#from mongoAuth import auth
from time import gmtime, strftime
import urllib.request
import re
notFound = json.loads('{"ERROR" : "No data found"}')
# Init MongoDB;
#MC = pymongo.MongoClient(auth['host'] + auth['port'])
# Init MySQL; (Database firewalled)
con = pymysql.connect("127.0.0.1","root","","test" )
cursor = con.cursor()
def get_real_ip():
print (str(request.remote_addr) + ' Client initiated request ->')
return (request.remote_addr)
# Flask rules
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
limiter = Limiter(app, key_func=get_real_ip, default_limits=["6/minute"])
app.url_map.strict_slashes = False
api = Api(app, prefix="/apiv1/free")
def checkInvalidChars(value):
regex = re.compile('[@_!#$%^&*()<>?/|}{~:,.}{+]')
if (regex.search(value) == None):
return 'OK'
else:
return 'FAIL'
# http://127.0.0.1:5000/apiv1/free/getDapp
class getDapp(Resource):
def get(self):
cursor.execute("select * from dapp LIMIT 10;")
return jsonify(data=cursor.fetchall())
# Routes
api.add_resource(getDapp, '/getDapp')
# Serve the high performance http server
if __name__ == '__main__':
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()

如您所见,输出只有没有键的值(也称为行(:

{ 
"data":[ 
[ 
1,
"b127a532-c5d0-4450-bcd2-5e9c9d5e79c6",
"Ether Tulips",
"http://ethertulips.com",
"",
"",
"games",
"eth",
"approved",
null,
0,
0,
"Sat, 03 Feb 2018 01:11:15 GMT",
"Wed, 11 Sep 2019 10:43:01 GMT",
0,
"[]",
0
]
]
}

任何如何实现键/值的帮助将不胜感激。

尝试使用 DictCursor。

根据 pymysql 的文档cursor应该创建一个接收游标类型的方法。

from pymysql.cursors import DictCursor
cursor = con.cursor(DictCursor)

最新更新