如何拦截猎鹰应用程序中的静态路由?

How can I intercept static routes in a falcon app?

我目前正在使用静态路由提供文件,如下所示:

application.add_static_route('/artifacts/', '/artifacts/')

如何将在每次 GET 之前调用的函数添加到此路由及其下方的任何路由?当任何用户试图从该路线获取工件时,我想向我们的 matomo(分析)服务器发送一些数据。

可以先加middleware to process every request before routing. The drawback is that this would apply to all incoming requests, so you might need to recheck req.path

class AnalyticsMiddleware:
    def process_request(self, req, resp):
        if req.path.startswith('/artifacts/'):
            print(f'Do something with {req.uri}...')


application = falcon.App(middleware=[AnalyticsMiddleware(), ...])

或者,您可以子类化 StaticRoute 并将其添加为接收器:

import falcon
import falcon.routing.static


class MyStaticRoute(falcon.routing.static.StaticRoute):
    def __call__(self, req, resp):
        print(f'Do something with {req.uri}...')

        super().__call__(req, resp)


# ...

static = MyStaticRoute('/artifacts/', '/artifacts/')
application.add_sink(static, '/artifacts/')

但是,后一种方法没有正式记录,因此理论上它可能会在未来的版本中中断,恕不另行通知。仅当中间件方法由于某种原因不能满足您的用例时才使用它。