使用基于类的vi在Flask中管理URL的可选动态段

2024-03-28 22:42:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想重现在使用基于Flask类的视图时将多个URL链接到一个端点的行为。 使用经典的烧瓶视图,我会:

@app.route("/users")
@app.route("/users/<int:id>", defaults={"id": None})
def users(id):
    # Function

但是如何使用基于类的视图重现这种行为app.add_url_规则? 在


Tags: none视图idappurlflask烧瓶链接
1条回答
网友
1楼 · 发布于 2024-03-28 22:42:04

{{1}在你提到的每个类的规则{1}之后,通常都是基于^ 1}定义的规则:

class UserAPI(MethodView):

    def get(self, user_id):
        if user_id is None:
            # return a list of users
            pass
        else:
            # expose a single user
            pass

    def post(self):
        # create a new user
        pass

    def delete(self, user_id):
        # delete a single user
        pass

    def put(self, user_id):
        # update a single user
        pass

然后您可以将路线添加为:

^{pr2}$

相关问题 更多 >