1. First, use python to query the mysql database code as follows:
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()
Change to the interface, using the Flask framework (you can compare and see what needs to be changed):
Post request (just replace get with 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)
The above implements a simple interface
But the above returns all the data, how to filter the data according to the conditions? For example, I want the piece of data whose name = Zhang Liang, and the operation is as follows.
The specific code is as follows:
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 searches as follows:
At this time, I found that the return is only a string, but if you want a standardized json format, you need to modify the assignment method of the for loop:
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)
During the process, I found that the interface request will report 500 to the server, and the server will report an error: TypeError: Object of type 'datetime' is not JSON serializable
The reason I finally found out is that the extracted value has a date format, and it is no problem to output it as a string str, but the json format cannot be recognized, as long as the format is converted when assigning a value: 'createtime': row[3].strftime("%Y-%m-%d %H:%M:%S")}
The query results are as follows:
Detailed explanation of how to use Postman: https://blog.csdn.net/fxbin123/article/details/80428216
Flask Chinese documentation: http://docs.jinkan.org/docs/flask/
Related reference link: https://www.cnblogs.com/testcoffee/p/6295970.html
https://www.jianshu.com/p/657c9be12e00
https://www.cnblogs.com/crss/p/8529002.html
————————————————
Copyright statement: This article is an original article by CSDN blogger "Steven灬", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/weixin_40547993/article/details/89632691