Python 除GET、PUT、POST、DELETE之外的其他RESTful自定义路由
在Flask RESTful中,我们添加了如下所示的api路由Python 除GET、PUT、POST、DELETE之外的其他RESTful自定义路由,python,flask,flask-restful,Python,Flask,Flask Restful,在Flask RESTful中,我们添加了如下所示的api路由 api.add_resource(CuteKitty,'/api/kitty') class CuteKitty(Resource): def get(self): return {} def post(self): return {} def put(self): return {} def delete(self): return None, 204 因此,GET/api/kitty-->to
api.add_resource(CuteKitty,'/api/kitty')
class CuteKitty(Resource):
def get(self): return {}
def post(self): return {}
def put(self): return {}
def delete(self): return None, 204
因此,GET/api/kitty
-->toCuteKitty.GET()
方法;对所有HTTP谓词都是这样
假设我需要为我的api消费者提供一个可爱的api,比如
POST /api/kitty/drink/milk ---> CuteKitty.drink(what="milk")
POST /api/kitty/meow ---> CuteKitty.meow()
如何使用api.add\u resource
class CuteKitty(Resource):
def get(self): return {}
def post(self): return {}
def put(self): return {}
def delete(self): return None, 204
def drink(self,what="milk"): return {}
def meow(self): return {}
Like wise how to add route Like
/api/kitty//habits
-->CuteKitty.habits(kitty_id)Flask RESTful专门通过解释HTTP请求方法来实现RESTful api。Drink和Meow不是标准的HTTP方法,因此Flask RESTful与资源中的Drink
和Meow
方法无关
解决方案是定义多个API路由:
api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/')
api.add_resource(DrinkingKitty, '/kitty/<int:kitty_id>/drink/<what>')
api.add_resource(MeowingKitty, '/kitty/<int:kitty_id>/meow/')
api.add_资源(CuteKitty,“/kitty/”)
api.add_资源(DrinkingKitty,“/kitty//drink/”)
api.add_资源(MeowingKitty,“/kitty//meow/”)
不那么直观(我认为更糟糕)的方法是创建frankenresource:
# still allow requests to hit just get/post/etc without invoking anything else
api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/')
api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/<task>/<path:args>/')
#仍然允许请求只点击get/post/etc,而不调用任何其他内容
api.add_资源(CuteKitty,“/kitty/”)
api.add_资源(CuteKitty,“/kitty/”)
然后用split(“/”)
来打断参数,并用它们调用task。或者,您可以将这些设置为URL参数(/endpoint/?task=drink&what=milk
),这仍然是一个有效的RESTful体系结构
您还可以对资源类进行子类化,并自己实现所需的功能——在本例中,我建议您看看Flask Classy是如何实现这一点的。或者,你也可以拿起经典的烧瓶,玩弄它,看看你有多喜欢它;然而,对于一个简单的API,我认为RESTful带来的不仅仅是Classy。步骤1:编写资源类
class CuteKitty(Resource):
def get(self): return {}
def post(self): return {}
def put(self): return {}
def delete(self): return None, 204
def meow(self): return {}
步骤2:在类之下,或在获得可调用
api.add_resource(CuteKitty,'/api/kitty/meow',endpoint='meow',methods=['GET'])
这消除了我的很多困惑,但我只是想,如果有机会我可以将属于
CuteKitty
的所有代码都放在一个文件/类中,那么剩下的ful似乎不允许这样做。我也不知道自己该为/endpoint//
写多少锅炉板代码。我想到现在为止,我会坚持写很多课。谢谢@justanr!对这个例子大发雷霆!:)