Locust 官方文档 9:扩展 Locust

Locust comes with a number of events hooks that can be used to extend Locust in different ways.

Locust 提供了很多的 events hooks,可以用来在不同情况下扩展 Locust。

Event hooks live on the Environment instance under the events attribute.

Event hooks 存在于 Environment 类的实例中的 events 属性。

However, since the Environment instance hasn’t been created when locustfiles are imported, the events object can also be accessed at the module level of the locustfile through the locust.events variable.

由于 Environment 实例在 locustfiles 导入时还未创建实例,事件对象也可以通过 locust.events 变量在 locustfile 中通过模块级别引入。

Here’s an example on how to set up an event listener:

以下是一个设置事件监听的示例:

from locust import events

@events.request_success.add_listener
def my_success_handler(request_type, name, response_time, response_length, **kw):
    print("Successfully made a request to: %s" % name)

Note

It’s highly recommended that you add a wildcard keyword argument in your listeners (the **kw in the code above), to prevent your code from breaking if new arguments are added in a future version.

注意:

强烈建议在监听器中添加通配符关键字参数(上面代码中的 **kw),以防止在以后的版本中添加新参数时导致监听器代码不可用。

See also

To see all available event, please see Event hooks.

如果要查看所有可用的事件,请参见 Event hooks。

添加 web 路由

Locust uses Flask to serve the web UI and therefore it is easy to add web end-points to the web UI.

Locust 使用 Flask 作为 web UI 的服务架构,因此很容易添加 web 端点到 Locust 的 web UI。

By listening to the init event, we can retrieve a reference to the Flask app instance and use that to set up a new route:

通过监听 init (初始化事件),我们可以引用 Flask app 的实例并为其设置一个新路由:

from locust import events

@events.init.add_listener
def on_locust_init(web_ui, **kw):
    @web_ui.app.route("/added_page")
    def my_added_page():
        return "Another page"

You should now be able to start locust and browse to http://127.0.0.1:8089/added_page

你现在应该可以启动 Locust 并通过浏览器查看 http://127.0.0.1:8089/added_page。

你可能感兴趣的:(Locust 官方文档 9:扩展 Locust)