Search code examples
pythontwisted

How to load custom configuration file with twisted?


I'm creating a simple server with twisted. I want to store config values in a yaml file. I can't find examples of configuring twisted services or applications with app-specific config.

Since the actual Resource object I'm serving will be created for each request, obviously this isn't the right place to read a config file.

Would I read the config file in my factory perhaps, and then subclass Site to pass it to my resource? I just can't seem to find the pattern documented anywhere.

Here's my code:

#!/usr/bin/env python

from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import yaml

def load_config():
    return yaml.load(file('./test/config_file.yaml', 'r'))

# how can I make this resource have access to my config?
class ScaledImage(Resource):
    isLeaf = True

    def render_POST(self, request):
        return """
<h1>image scaled</h1>
    """

factory = Site(ScaledImage())
reactor.listenTCP(8000, factory)
reactor.run()

Solution

  • How about just changing this:

    factory = Site(ScaledImage(load_config(...)))
    

    Then make your ScaledImage initializer accept the configuration.

    As a general point, you probably shouldn't pass your entire configuration around. Configuration files usually end up as big confusing balls of random stuff. You don't want to push this big mess through your APIs. Instead, pick out the piece of configuration that ScaledImage is interested in and pass that in:

    config = load_config(...)
    scaleFactor = getScaleFactorFromConfig(config)
    factory = Site(ScaledImage(scaleFactor))