Gunicorn: Server Hooks Usage Example

Created on 16 Oct 2019  路  7Comments  路  Source: benoitc/gunicorn

Despite reading the documentation (below) and searching elsewhere, it's not clear to me how I can interface with gunicorn's server hooks.

Could someone provide an example of how this could be done from within the scope of a (Python 3) application?

I would be willing to add this content to the documentation as thanks.

Server Hooks Documentation

https://docs.gunicorn.org/en/stable/settings.html#server-hooks

Documentation help wanted

Most helpful comment

Solved.

You want to use a configuration file written in Python, use the argument --config my_config.py, and set the variable of the hook to a function pointer.

Example

config.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import server

bind = '0.0.0.0:8000'
workers = 4
loglevel = "info"

# Server Hooks
on_starting = server.on_starting

server.py

def on_starting(server):
    app.logger.info("Starting Server")

Invocation

gunicorn server:app --config config.py

All 7 comments

Solved.

You want to use a configuration file written in Python, use the argument --config my_config.py, and set the variable of the hook to a function pointer.

Example

config.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import server

bind = '0.0.0.0:8000'
workers = 4
loglevel = "info"

# Server Hooks
on_starting = server.on_starting

server.py

def on_starting(server):
    app.logger.info("Starting Server")

Invocation

gunicorn server:app --config config.py

Leaving the issue open to address the matter of documentation, which I think should be improved for clarity's sake.

I had to do a decent amount of digging to figure out how this works.

We could link to this more prominently, but there are examples for this here: https://github.com/benoitc/gunicorn/blob/master/examples/example_config.py

@tilgovi, yeah I think would definitely be a good idea. I found that after I had already determined how the configuration file works by going through other issues.

@polly-want-a-kraken any PR is welcome ;)

I'm guessing that on_starting = server.on_starting is superfluous? The linked config example suggests like you should be able to just define a hook function in the config file and have it work.

@TMiguelT correct.

Was this page helpful?
0 / 5 - 0 ratings