有多达HTTP框架使用自定义方法和自定义HTTP状态代码在代码内部使用的支持,我想知道Falcon是否可以做同样的事情?
我尝试过:
// create html page dynamically
// run some code before print
window.onafterprint = function() {
// run some code after print
}
window.print();
,我也将其添加到class MyResource:
def on_obtain(self, req, resp):
# do some thing
路由中,但是当我调用此API时,我得到的API
如下:
HTTP/1.1 400 Bad Request
我的问题是可以在此资源上定义{"title":"Bad request","description":"Invalid HTTP method"}
吗?
答案 0 :(得分:3)
我认为您需要使用Custom Routers。只是一个例子:
class Resource:
def on_get(self, req, resp):
resp.body = req.method
resp.status = falcon.HTTP_200
def on_example(self, req, resp):
resp.body = req.method
resp.status = falcon.HTTP_200
class MyRouter(routing.DefaultRouter):
# this is just demonstration that my solution works
# I added request method into method_map
def add_route(self, uri_template, method_map, resource):
super().add_route(uri_template, method_map, resource)
method_map['EXAMPLE'] = resource.on_example
def find(self, uri, req=None):
return super().find(uri, req)
api = falcon.API(router=MyRouter()) # just set your router
test = Resource()
api.add_route('/test', test)
让我们检查一下:
curl -X EXAMPLE http://127.0.0.1:8000/test
EXAMPLE⏎
curl http://127.0.0.1:8000/test
GET⏎
因此,您只需要创建Router
并实现add_route()
/ find()
方法即可。希望你明白我的意思。