2016-07-23 53 views
1

我想重現在使用基於Flask類的視圖時使多個URL鏈接到一個端點的行爲。 採用經典的瓶的意見,我會做:使用基於類的視圖管理Flask中URL的可選動態段

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

但如何重現使用app.add_url_rule基於類視這種行爲?

回答

1

通常情況下,當你定義了基於類的視圖,只是add_url_rule每條路由的規則,同時在Flask's Docs提到的例子:

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 

然後你就可以添加你的路線爲:

user_view = UserAPI.as_view('user_api') 
app.add_url_rule('/users/', defaults={'user_id': None}, 
       view_func=user_view, methods=['GET',]) 
app.add_url_rule('/users/', view_func=user_view, methods=['POST',]) 
app.add_url_rule('/users/<int:user_id>', view_func=user_view, 
       methods=['GET', 'PUT', 'DELETE'])