WSGI helpers

Various helpers for WSGI applications.

kw.platform.wsgi.user_agent_middleware = <_MiddlewareFactory at 140286417861936 wrapping <function _validate_user_agent>>

Validate client’s User-Agent header and modify response based on that.

If the User-Agent header is invalid, there are three possible outcomes:

  1. The current time is less then settings.KIWI_REQUESTS_SLOWDOWN_DATETIME, do nothing in this case.

  2. The current time is less then settings.KIWI_REQUESTS_RESTRICT_DATETIME, slow down the response twice the normal responce time.

  3. The current time is more then settings.KIWI_REQUESTS_RESTRICT_DATETIME, refuse the request, return HTTP 400 to the client.

Usage:

from your_app import wsgi_app

wsgi_app = user_agent_middleware(wsgi_app)

For example, in Flask, the middleware can be applied like this:

from flask import Flask

app = Flask(__name__)
app.wsgi_app = user_agent_middleware(app)

app.run()

In Django, you can apply the middleware like this:

from django.core.wsgi import get_wsgi_application

application = user_agent_middleware(get_wsgi_application())

For more information see Django docs.

Warning

The middleware slows down requests by calling time.sleep() (in the time frame when requests with invalid user-agent are being delayed). This can increase worker busyness which can overload a service.