【问题标题】:testdriven.io: Test-Driven Development with FastAPI and Docker: Get routes not working togethertestdriven.io:使用 FastAPI 和 Docker 进行测试驱动开发:获取无法协同工作的路由
【发布时间】:2022-01-03 22:07:43
【问题描述】:

我正在学习 testdriven.io 课程。

我发现通过添加 GET All users 路由不起作用,因为请求需要用户 ID。

在 users.py 文件中我有:

    def get(self):  
        return User.query.all(), 200

def get(self, user_id):  
     ...  

然后有

api.add_resource(UsersList, '/users')  
api.add_resource(UsersList, '/users/<int:user_id>')  

似乎通过包含 '/users' 路由失败的 '/users/int:user_id' 路由:

src/tests/test_users.py::test_all_users - TypeError: get() missing 1 required positional argument: 'user_id'

如果我注释掉 api.add_resource(UsersList, '/users/int:user_id') 路由,那么所有用户路由都可以正常工作。

有没有办法让(所有用户和用户 ID 的用户)路由都工作?

我能在 Lumen 等其他框架中做类似的事情吗(PHP 所以可能遗漏了一些明显的东西。

谢谢

贾斯

【问题讨论】:

  • 我想这可行:@api.marshal_with(user)。 def get(self, user_id=None): if user_id is None: return User.query.all(), 200 user= User.query.filter_by(id=user_id).first() if not user: api.abort(404 , f"用户 {user_id} 不存在")。返回用户,200

标签: python flask flask-restx


【解决方案1】:

我认为这可能是答案,但我希望能够添加多个 GET 函数来分离代码。

这个:

以相同的方法处理 /users 和 users/id 路由。是否可以同时拥有 GET 功能并分离逻辑/代码。

    @api.marshal_with(user)
    def get(self, user_id=None):
        if user_id is None:
            return User.query.all(), 200

        user= User.query.filter_by(id=user_id).first()
        if not user:
            api.abort(404, f"User {user_id} does not exist")

        return user, 200

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    相关资源
    最近更新 更多