python编写一个接口,链接mysql数据库查询数据

python编写一个接口,链接mysql数据库查询数据,第1张

python编写一个接口链接mysql数据库查询数据

1、首先,使用python查询mysql数据库代码如下:

import MySQLdb

def getcontent():
    db = MySQLdb.connect('localhost', 'root', '1qaz!QAZ', 'zlnewschema', charset='utf8')
    cursor = db.cursor()
    sql = 'select * from user;'
    cursor.execute(sql)
    usercontent = cursor.fetchall()
    print(usercontent)
    for row in usercontent:
        fname = row[0]
        femail = row[1]
        fpw = row[2]
        ftime = row[3]
        print('name=%s,email=%s,password=%s,createtime=%s' %(fname, femail, fpw,ftime))
    db.close()

if __name__ == '__main__':
    getcontent()

改为接口,用的Flask框架(可以对比看看需要改哪些地方):

Post请求(get直接换成get就行了):

import MySQLdb
import json
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,request
# from flask_cors import *
app = Flask(__name__)


@app.route('/index1', methods=['POST'])
def getcontent():
    db = MySQLdb.connect('localhost', 'root', '1qaz!QAZ', 'zlnewschema', charset='utf8')
    cursor = db.cursor()
    sql = 'select * from user;'
    cursor.execute(sql)
    usercontent = cursor.fetchall()
    print(usercontent)
    userjson = []
    for row in usercontent:
        fname = row[0]
        femail = row[1]
        fpw = row[2]
        ftime = row[3]
        # print('name=%s,email=%s,password=%s,createtime=%s' %(fname, femail, fpw,ftime))
        user = 'name=%s,email=%s,password=%s,createtime=%s' %(fname, femail, fpw,ftime)
        userjson.append(user)
    db.close()
    return json.dumps(userjson, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    # getcontent()
    app.run(host='0.0.0.0', port=5590)

上面实现了一个简单的接口

但是上面返回的是所有的数据,怎么根据条件去筛选数据呢?比如我就想要 name = 张亮 的那条数据, *** 作如下。

具体代码如下:

import MySQLdb
import json
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,request
# from flask_cors import *
app = Flask(__name__)


@app.route('/index1', methods=['POST'])
def zlindex():
    inputData = request.json.get('username')
    userdata = getcontent(inputData)
    return userdata


def getcontent(inputData):
    db = MySQLdb.connect('localhost', 'root', '1qaz!QAZ', 'zlnewschema', charset='utf8')
    cursor = db.cursor()
    sql = "select * from user where username = '%s';" %(inputData)
    cursor.execute(sql)
    usercontent = cursor.fetchall()
    print(usercontent)
    userjson = []
    for row in usercontent:
        fname = row[0]
        femail = row[1]
        fpw = row[2]
        ftime = row[3]
        # print('name=%s,email=%s,password=%s,createtime=%s' %(fname, femail, fpw,ftime))
        user = 'name=%s,email=%s,password=%s,createtime=%s' %(fname, femail, fpw,ftime)
        userjson.append(user)
    db.close()
    return json.dumps(userjson, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    # getcontent()
    app.run(host='0.0.0.0', port=5590)

postman搜索如下:

这时候,发现返回的只是一个字符串,然而想要一个标准化的json格式的话,就需要修改一下for循环的赋值方法:

import MySQLdb
import json
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,request
# from flask_cors import *
app = Flask(__name__)


@app.route('/index1', methods=['POST'])
# def zlindex():
#     inputData = request.json.get('username')
#     userdata = getcontent(inputData)
#     return userdata


def getcontent():
    db = MySQLdb.connect('localhost', 'root', '1qaz!QAZ', 'zlnewschema', charset='utf8')
    cursor = db.cursor()
    sql = "select * from user"
    # sql = "select * from user where username = '%s';" %(inputData)
    cursor.execute(sql)
    usercontent = cursor.fetchall()
    print(usercontent)
    userjson = []
    for row in usercontent:
        # fname = row[0]
        # femail = row[1]
        # fpw = row[2]
        # ftime = row[3]
        # print('name=%s,email=%s,password=%s,createtime=%s' %(fname, femail, fpw,ftime))
        user = {'name': row[0], 'email': row[1], 'password': row[2], 'createtime': row[3].strftime("%Y-%m-%d %H:%M:%S")}
        # print(user)
        userjson.append(user)
        # print(userjson)
    db.close()
    return json.dumps(userjson, ensure_ascii=False, indent=4)  # 返回一个字典格式


if __name__ == '__main__':
    # getcontent()
    app.run(host='0.0.0.0', port=5590)

过程中发现,接口请求会报服务端500,服务端报错为:TypeError: Object of type 'datetime' is not JSON serializable 

最后找到的原因,是提取的值里有日期格式,作为一个字符串str输出无问题,但是json格式不能识别,只要赋值时转换下格式就行:'createtime': row[3].strftime("%Y-%m-%d %H:%M:%S")}

查询结果如下:

 

Postman使用方法详解:https://blog.csdn.net/fxbin123/article/details/80428216

Flask中文文档:http://docs.jinkan.org/docs/flask/

相关参考链接:https://www.cnblogs.com/testcoffee/p/6295970.html

                            https://www.jianshu.com/p/657c9be12e00

                            https://www.cnblogs.com/crss/p/8529002.html
————————————————
版权声明:本文为CSDN博主「Steven灬」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_40547993/article/details/89632691

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5721591.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存