需要接收一个json对象,然后判断主键是否存在后执行插入操作
服务端
from flask import Flask, request, jsonify
from gevent import pywsgi
import pymysql
import config
import json
app = Flask(__name__)
try:
mysql_conn = pymysql.connect(host=config.mysql_host,user=config.mysql_user,passwd=config.mysql_password,port=config.mysql_port, charset=config.mysql_charset, database=config.mysql_database)
mysql_cursor = mysql_conn.cursor()
print('mysql连接成功')
except Exception as e:
print(e)
# 定义接口
@app.route('/insert_database', methods=['POST'])
def get_name():
try:
data = request.get_json()
print(f'接收数据: {data}')
select_sql = f"SELECT ID FROM `{config.mysql_table}` WHERE `CheckDeviceName`='{data['CheckDeviceName']}' AND `FillerOrderNumber`='{data['FillerOrderNumber']}' AND `CheckDate`='{data['CheckDate']}'"
res = mysql_cursor.execute(select_sql)
if res >= 1:
print('已存在该条数据')
return jsonify(status="exists")
insert_sql = f'''INSERT INTO `{config.mysql_table}` VALUES(null, FALSE, '{data['PatientCheckId']}', '{data['CheckDeviceName']}', '{data['FillerOrderNumber']}', '{data['PatientName']}', '{data['PatientSex']}', '{data['PatientIdCard']}', '{data['CheckDate']}', '{data['CheckTime']}', '', '', '{data['SpecimenSource']}', '{data['CheckResult']}', '', '', '')'''
mysql_cursor.execute(insert_sql)
mysql_conn.commit()
print('数据插入成功')
return jsonify(status="success")
except Exception as e:
print(e)
return jsonify(status="error")
if __name__ == '__main__':
server = pywsgi.WSGIServer((config.host,config.port), app)
server.serve_forever()
requests测试
import requests
import json
url = 'http://localhost:8000/insert_database'
data = {'CheckDeviceName': 'DH71_CRP', 'FillerOrderNumber': '1001', 'CheckDate': '2023-06-12'}
response = requests.post(url, json=data)
if response.status_code == 200:
result = response.json()
print(result)
else:
print('请求失败')
标签:python,data,Flask,json,mysql,print,import,config
From: https://www.cnblogs.com/wstong2052/p/17475833.html