【发布时间】:2019-12-07 06:50:09
【问题描述】:
我有一个有效的 SQL 存储过程,并在 Python 中设置了 flask-sqlAlchemy 并连接到我的 MySQL 数据库。我正在尝试构建一个简单的 API,它将接收通过 URL 请求输入的 6-7 个请求参数并将它们发送到我的调用过程,并根据在 DB 表中插入新记录的存储过程相应地更新数据库( sp 是下面的“add_spotting”)。
我正在尝试通过 POST 方法执行此操作,并相信我正确地接收了请求参数并调用了该过程,但我不确定如何执行这些过程并实际注入数据库。
class Spotting(mysql.Model):
__tablename__ = 'spotting'
spotting_id = mysql.Column(mysql.Integer, primary_key = True)
animal_id = mysql.Column(mysql.Integer, mysql.ForeignKey('animal.animal_id'), nullable=False)
user_id = mysql.Column(mysql.Integer, mysql.ForeignKey('user.user_id'), nullable=False)
trail_id = mysql.Column(mysql.Integer, mysql.ForeignKey('trail.trail_id'), nullable=False)
quantity = mysql.Column(mysql.Integer, nullable = False)
lat = mysql.Column(mysql.Float, nullable=True)
lon = mysql.Column(mysql.Float, nullable=True)
description = mysql.Column(mysql.String(250), nullable=False)
#Post method
@application.route('/spotting', methods=['POST'])
def postSpotting():
animal = request.args.get('animal')
user = request.args.get('user')
trail = request.args.get('trail')
quantity = request.args.get('quantity')
lat = request.args.get('lat')
lon = request.args.get('lon')
desc = request.args.get('desc')
proc_call = "call add_spotting('" + animal + "','"+ user + "','" + trail + \
"','" + quantity + "','" + lat + "','" + lon + "','" + desc + "')"
mysql.engine.execute(proc_call)
### Here I want to post and commit this to the MySQL DB via the stored proc and return a message such as
# ## 'Spotting successfully added'
return ("Successfully posted!")
【问题讨论】:
-
嗨@Shane,你介意分享数据库模型的代码吗?
-
@calestini 当然!我在上面添加了它——我不确定我的数据模型是否完整,或者我是否真的需要它来用于这个 post 方法。我已经用数据填充并存储了我的数据库,因此我不需要通过 Python 创建它,但我确实希望能够使用 API 来演示通过我的存储过程进行的简单插入。
标签: python stored-procedures flask sqlalchemy flask-sqlalchemy