0

我是 API 新手,我正在创建一个 Flask Restful API。我想知道我是否需要为我想在我的数据库中执行的任何行操作创建新的模型和资源类?例如,我在我的数据库中创建了一个学生。在创建时他没有任何成绩,所以我创建了 StudentModel 和 StudentResource 并使用了表 Student。当我需要使用 PUT 请求更新成绩时,我是否需要创建一个 SudentGradeModel 和 StudentGradeResource 也访问学生表?

每个 Model 类都包含 Resource 类通过导入 Model 类使用的辅助函数。资源类只有 GET、POST、PUT 和 DELETE 方法。

class StudentModel(db.Model):
    __tablename__ = 'Student'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    class_sec = db.Column(db.String(4))
    
    def __init__(self, id, name, class_sec):
        self.id = id
        self.name= name
        self.class_sec = class_sec    

from flask_restful import Resource, reqparse

from models.student_model import StudenteModel


# noinspection PyMethodMayBeStatic
class StudentResource(Resource):

    parser = reqparse.RequestParser()
    parser.add_argument('id', type=int, required=True, help='Every Student must have an ID')
    parser.add_argument('name', type=str, required=True, help='Every Student must have a name')
    parser.add_argument('class', type=str, required=True, help='Every Student must be assigned a class and section')

    def get(self, id):
        pass

    def post(self, id):
        pass

class StudentGradeModel(db.Model):
    __tablename__ = 'Student'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    grade = db.Column(db.String(2), primary_key=True)
    
    def __init__(self, id, grade):
        self.id = id
        self.grade = grade
# noinspection PyMethodMayBeStatic
class StudentGradeResource(Resource):

    parser = reqparse.RequestParser()
    parser.add_argument('id', type=int, required=True, help='Student must have an ID to access table')
    parser.add_argument('grade', type=str, required=True, help='Student must have a grade to be assigned')

    def get(self, id):
        pass

    def post(self, id):
        pass

同样,如果我只想更新该部分,我是否必须使用 PUT 请求创建一个类似的 Classe。

谢谢你

4

1 回答 1

0

从这个问题来看,我假设一个学生只能有一个成绩或根本没有成绩,因为如果他们可以有多个成绩,则成绩必须在单独的表格中。

创建表的 SQL 如下所示:

CREATE TABLE student (
  id INT PRIMARY KEY,
  name VARCHAR(30) NOT NULL,
  class_sec CHAR(4) NOT NULL,
  grade INTEGER
);

(我更改了等级的数据类型,因为不应将数字数据存储为字符串)


不,你不能也不应该有两个模型用于同一张桌子。模型应该代表表格本身。

class StudentModel(db.Model):
    __tablename__ = 'Student'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    class_sec = db.Column(db.String(4), nullable=False)
    grade = db.Column(db.Integer)
    
    def __init__(self, id, name, class_sec):
        self.id = id
        self.name= name
        self.class_sec = class_sec

另一方面,您可以拥有多个资源来连接表。但是,每个资源都与一个路线相关联,您不应该有单独的成绩资源,除非您需要另一条路线,我认为您不需要。

class Student(Resource):
    ...
    def put(self, id):
        request_body = request.get_json()
        # do your things here
于 2020-08-21T05:09:42.443 回答