从Flask自定义验证

时间:2017-08-15 12:04:59

标签: python flask flask-sqlalchemy flask-restful

我正在使用flask_restful,我希望have custom validationproject_deadlines()方法将在数据库中查询有效值列表。

from flask import Flask, request, jsonify
from flask_restful import Resource, Api, reqparse
from flask_restful import reqparse

class CreateProject(Resource):
    def project_deadlines(self, value):
        deadline_ids = [item[0] for item in get_all_deadlines()]
        if not value in deadline_ids:
            raise ValueError("The given deadline ID '{}' does not exist.".format(value))

        return value

    def post(self):
        parser.add_argument('deadline_id', required=True, location='json',
            type=self.project_deadlines, help="Invalid Deadline ID given.")
        args = parser.parse_args()


def get_all_deadlines(self):
        return self.session.query(Deadline.deadline_id, Deadline.deadline_time).all()

这是模型类。 SQLAlchemy代码已被删除。

class Deadline(Base):
    __tablename__ = 'deadline'

    deadline_id = Column(Integer, primary_key = True)
    deadline_time = Column(String, nullable = False)
    deadline_description = Column(String, nullable = False)

    def __repr__(self):
        return "Deadlind(deadline_id={self.deadline_id}, "\
                      "deadline_time='{self.deadline_time}', "\
                      "deadline_description='{self.deadline_description}'), ".format(self=self)

问题

如何将Invalid Deadline ID given.作为输出,而不是输出The given deadline ID 'xxx' does not exist

0 个答案:

没有答案