Builder API¶
The Builder API defines a pluggable builder framework for manipulating nginx configs from within python.
Building a config¶
Every config built using the builder pattern starts off with creating a :class:NginxConfigBuilder:
from nginx.config.builder import NginxConfigBuilder
nginx = NginxConfigBuilder()
By default, this comes loaded with a bunch of helpful tools to easily create routes and servers in nginx:
with nginx.add_server() as server:
server.add_route('/foo').end()
with server.add_route('/bar') as bar:
bar.add_route('/baz')
This generates a simple config that looks like this:
error_log logs/nginx.error.log;
worker_processes auto;
daemon on;
http {
include ../conf/mime.types;
server {
server_name _;
location /foo {
}
location /bar {
location /baz {
}
}
}
}
events {
worker_connections 1024;
}
Plugins¶
A plugin is a class that inherits from nginx.config.builder.baseplugins.Plugin
that provides
additional methods which can be chained off of the NginxConfigBuilder
object. These plugins provide
convenience methods that manipulate the underlying nginx configuration that gets built by the
NginxConfigBuilder
.
A simple plugin only needs to define what methods it’s going to export:
class NoopPlugin(Plugin):
name = 'noop'
@property
def exported_methods(self):
return {'noop': self.noop}
def noop(self):
pass
This NoopPlugin provides a simple function that can be called off of a NginxConfigBuilder
that
does nothing successfully. More complex plugins can be found in nginx.config.builder.plugins
To use this NoopPlugin, we need to create a config builder and then register the plugin with it:
nginx = NginxConfigBuilder()
nginx.noop() # AttributeError :(
nginx.register_plugin(NoopPlugin())
nginx.noop() # it works!
A more complex plugin would actually do something, like a plugin that adds an expiry directive to a route:
class ExpiryPlugin(Plugin):
name = 'expiry'
@property
-
class
nginx.config.builder.
NginxConfigBuilder
(worker_processes='auto', worker_connections=512, error_log='logs/error.log', daemon='off')[source]¶ Helper that builds a working nginx configuration
Exposes a plugin-based architecture for generating nginx configurations.
-
register_plugin
(plugin)[source]¶ Registers a new nginx builder plugin.
Plugins must inherit from nginx.builder.baseplugins.Plugin and not expose methods that conflict with already loaded plugins
Parameters: nginx.builder.baseplugins.Plugin (plugin) – nginx plugin to add to builder
-
top
¶ Returns the logical top of the config hierarchy.
This is a convenience method for any plugins that need to quickly access the top of the config tree.
:returns
nginx.config.Block
: Top of the config block
-