python - 在猎鹰中添加自定义 HTTP 方法?

标签 python python-3.x falconframework

尽可能多的 HTTP 框架支持在代码中使用自定义方法和自定义 HTTP 状态代码,我想知道是否可以用 Falcon 做同样的事情?

我试过:

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"}

我的问题是是否可以在此资源上定义obtain

最佳答案

我认为你需要使用 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() 方法即可。希望你明白我的意思。

关于python - 在猎鹰中添加自定义 HTTP 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52688122/

相关文章:

python - 如何将变量从中间件传递到猎鹰中的资源?

python - 如何使用 pandas 填充数据框中特定类别数据的缺失数据?

python - 在Python中访问大量未排序的数组元素

python - 打印 [Python] 在 Pycharm 中被视为关键字

python - python中的打印输出(输入输出过程)

python - 返回我的错误是 `Access denied for user ' root' @'localhost'(使用密码 : YES )`. Even when I use ` mike`

python - 如何保护仅服务于我的前端的自己的后端 API?

python - 将 Numpy 3D 数组乘以 1D 数组

python - 访问子类父类中重写的类变量

python - 如何使用 Falcon 配置测试环境