Flask-RESTful的资源和路由设计示例(二)

2023-05-06 15:42:41 浏览数 (1)

接下来,我们将扩展这个示例应用程序,添加更多的资源和路由设计。

假设我们希望添加一个 Group 资源类,用于处理用户组相关的请求。每个用户可以属于多个组,每个组也可以包含多个用户。以下是示例代码:

代码语言:javascript复制
class Group(Resource):
    def get(self, group_id):
        if group_id not in groups:
            return {'message': f'Group {group_id} not found'}, 404
        return groups[group_id]

    def post(self, group_id):
        if group_id in groups:
            return {'message': f'Group {group_id} already exists'}, 400
        groups[group_id] = {'name': request.json['name'], 'members': []}
        return groups[group_id]

    def put(self, group_id):
        if group_id not in groups:
            return {'message': f'Group {group_id} not found'}, 404
        groups[group_id]['name'] = request.json['name']
        return groups[group_id]

    def delete(self, group_id):
        if group_id not in groups:
            return {'message': f'Group {group_id} not found'}, 404
        del groups[group_id]
        return {'message': f'Group {group_id} deleted'}

class UserGroup(Resource):
    def get(self, user_id):
        if user_id not in users:
            return {'message': f'User {user_id} not found'}, 404
        user_groups = []
        for group_id in groups:
            if user_id in groups[group_id]['members']:
                user_groups.append({'id': group_id, 'name': groups[group_id]['name']})
        return user_groups

    def post(self, user_id):
        if user_id not in users:
            return {'message': f'User {user_id} not found'}, 404
        group_id = request.json['group_id']
        if group_id not in groups:
            return {'message': f'Group {group_id} not found'}, 404
        if user_id in groups[group_id]['members']:
            return {'message': f'User {user_id} already in group {group_id}'}, 400
        groups[group_id]['members'].append(user_id)
        return {'message': f'User {user_id} added to group {group_id}'}

    def delete(self, user_id):
        if user_id not in users:
            return {'message': f'User {user_id} not found'}, 404
        group_id = request.json['group_id']
        if group_id not in groups:
            return {'message': f'Group {group_id} not found'}, 404
        if user_id not in groups[group_id]['members']:
            return {'message': f'User {user_id} not in group {group_id}'}, 400
        groups[group_id]['members'].remove(user_id)
        return {'message': f'User {user_id} removed from group {group_id}'}

api.add_resource(Group, '/groups/<int:group_id>')
api.add_resource(UserGroup, '/users/<int:user_id>/groups')

在上面的代码中,我们首先定义了一个名为 Group 的资源类,用于处理用户组相关的请求。每个组对象包含一个名为 name 的属性和一个名为 members 的列表,用于存储属于该组的用户 ID。

0 人点赞