gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:14:55 25 4
gpt4 key购买 nike

我使用 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 .

根据documentation of pymysql应创建一个方法 cursor 接收光标类型。

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

关于Python Flask REST API MySQL 获取游标键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59748410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com