【问题标题】:Python Flask REST API MySQL get cursor keys and valuesPython Flask REST API MySQL 获取光标键和值
【发布时间】:2020-01-15 09:28:15
【问题描述】:

我使用 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
  ]
 ]
}

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

【问题讨论】:

    标签: python mysql api flask


    【解决方案1】:

    尝试使用DictCursor

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 2019-01-31
      • 2019-02-23
      相关资源
      最近更新 更多