我如何 return Flask-restful 中的错误消息?
How do I return an error message in Flask-resful?
我在 Post 方法上添加了一个检查,只允许不同日期的约会通过,但我不知道如何 return 一个错误消息。这是代码
from flask_restful import Resource, Api, request
from package.model import conn
class Appointments(Resource):
def get(self):
appointment = conn.execute("SELECT p.*,d.*,a.* from appointment a LEFT JOIN patient p ON a.pat_id = p.pat_id LEFT JOIN doctor d ON a.doc_id = d.doc_id ORDER BY appointment_date DESC").fetchall()
return appointment
def post(self):
appointment = request.get_json(force=True)
pat_id = appointment['pat_id']
doc_id = appointment['doc_id']
appointment_date = appointment['appointment_date']
a = conn.execute("SELECT count(*) From appointment WHERE doc_id =?
AND appointment_date=?",(doc_id,appointment_date,)).fetchone()
if a['count(*)'] == 0:
appointment['app_id'] = conn.execute('''INSERT INTO appointment(pat_id,doc_id,appointment_date)VALUES(?,?,?)''', (pat_id, doc_id,appointment_date)).lastrowid
conn.commit()
return appointment
else:
pass
我用什么 return 代替 pass 语句?
PS:对于上下文,我正在努力改进 https://github.com/tushariscoolster/HospitalManagementSystem
Flask-Restful 提供了一个 abort
函数,它可以引发带有特殊 HTTP 代码的 HTTPException 并将消息返回给客户端。
因此,您可以尝试更改如下代码:
from flask_restful import abort
class Appointments(Resource):
def post(self):
# ignore some code
if a['count(*)'] == 0:
# ignore some code
else:
abort(403, error_message='just accept an appointment on special date')
然后,客户端将收到 403 和一个有效的 JSON 字符串,如下所示:
{"error_message":"just accept an appointment on special date"}
最后,客户端要妥善处理错误信息。
我在 Post 方法上添加了一个检查,只允许不同日期的约会通过,但我不知道如何 return 一个错误消息。这是代码
from flask_restful import Resource, Api, request
from package.model import conn
class Appointments(Resource):
def get(self):
appointment = conn.execute("SELECT p.*,d.*,a.* from appointment a LEFT JOIN patient p ON a.pat_id = p.pat_id LEFT JOIN doctor d ON a.doc_id = d.doc_id ORDER BY appointment_date DESC").fetchall()
return appointment
def post(self):
appointment = request.get_json(force=True)
pat_id = appointment['pat_id']
doc_id = appointment['doc_id']
appointment_date = appointment['appointment_date']
a = conn.execute("SELECT count(*) From appointment WHERE doc_id =?
AND appointment_date=?",(doc_id,appointment_date,)).fetchone()
if a['count(*)'] == 0:
appointment['app_id'] = conn.execute('''INSERT INTO appointment(pat_id,doc_id,appointment_date)VALUES(?,?,?)''', (pat_id, doc_id,appointment_date)).lastrowid
conn.commit()
return appointment
else:
pass
我用什么 return 代替 pass 语句?
PS:对于上下文,我正在努力改进 https://github.com/tushariscoolster/HospitalManagementSystem
Flask-Restful 提供了一个 abort
函数,它可以引发带有特殊 HTTP 代码的 HTTPException 并将消息返回给客户端。
因此,您可以尝试更改如下代码:
from flask_restful import abort
class Appointments(Resource):
def post(self):
# ignore some code
if a['count(*)'] == 0:
# ignore some code
else:
abort(403, error_message='just accept an appointment on special date')
然后,客户端将收到 403 和一个有效的 JSON 字符串,如下所示:
{"error_message":"just accept an appointment on special date"}
最后,客户端要妥善处理错误信息。