使用POS方法传入一个参数返回MySQL查询结果
from flask import Flask, jsonify
from flask import abort
from flask import make_response
from flask import request
import pymysql
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/report/zeg_collect_store_report/tasks', methods=['POST'])
def create_task():
rows = []
if not request.json:
abort(400)
storeId = request.json['storeId']
connection = pymysql.connect(host='192.168.xx.xxx',
user='data_center',
password='xxxxxx',
db='data_center',
port=3306,
charset='utf8'
)
try:
# 获取一个游标
with connection.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
sql = "select * from zeg_collect_store_report where store_id={}".format(storeId)
# 根据传入的storeId拼接SQL查询数据
cursor.execute(sql)
for row in cursor.fetchall():
# TypeError: Object of type 'Decimal' is not JSON serializable Decimal类型转为string进行序列化
row['total_money'] = str(row['total_money'])
#print(row)
# print(type(row))
rows.append(row)
#print(rows)
except:
print('程序异常!')
return jsonify({'row': rows}), 201
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
# 若开启调试模式,且缺省host,则只有自己电脑可以访问,其他电脑无法访问,故配置host和port
app.run(host='192.168.aaa.bbb', port='5000', debug=True)
# windows执行命令 curl -i -H "Content-Type: application/json" -X POST -d {"""storeId""":"""1000"""} http://192.168.aaa.bbb:5000/report/zeg_collect_store_report/tasks
# Linux执行命令 curl -i -H "Content-Type: application/json" -X POST -d '{"storeId":"1000"}' http://192.168.aaa.bbb:5000/report/zeg_collect_store_report/tasks