2017-06-17 51 views
1

我添加了一個Post方法的檢查,只允許約會在不同的日期通過,但我不知道如何返回錯誤消息。這裏的代碼如何在Flask-resful中返回錯誤消息?

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 

我該如何返回,而不是通過聲明?

PS:對於情況下,我想提高https://github.com/tushariscoolster/HospitalManagementSystem

回答

1

瓶的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"} 

最後,客戶端應該正確處理錯誤信息。

相關問題