0

Essentially, when the pyramid app starts, I need to parse a file and make the data from that file available to the whole app. On top of that, I need to monitor the file for changes, it's essentially a config file. I was considering just making a singleton and initializing it when the app starts up when Configurator is initialized. Is that the best way to do it, or are there any other approaches I should follow/consider?

Sorry, new to pyramid and python, thank you!

2 Answers2

1

We do this exact thing (with Pyramid and global app settings) with a top-level app/config.py which is just a list of config variables (and possibly their defaults). Then in our main function we load the config and set the various attributes of the config module so the application can use them.

For example, here's app/config.py:

image_dir = '/mnt/images'
s3_access_key = None  # these must be specified in the config INI
s3_secret_key = None

Here's the relevant part of our config INI (eg: app/development.ini):

[app:main]
app.image_dir = ./test_images
app.s3_access_key = ABCD1234...
app.s3_secret_key = EFGH5678...

And the relevant config loading code in our app/main.py:

from . import config

def main(global_config, **settings):
    config.image_dir = settings.get('app.image_dir', config.image_dir)
    config.s3_access_key = settings['app.s3_access_key']
    config.s3_secret_key = settings['app.s3_secret_key']

    configurator = Configurator(settings=settings)
    # ... configure and add routes
    configurator.scan()

    return configurator.make_wsgi_app()

And then other application code can simply from app import config or from . import config and use the settings, for example: os.path.join(config.image_dir, 'my_image.jpg')

Ben Hoyt
  • 10,694
  • 5
  • 60
  • 84
0

As noted in many places, Singleton is considered a code smell and as such, should be avoided. IMHO, a Singleton can be used if there's a reasonable trade-off. For example, if using a Singleton boosts the performance in a significant way. In your situation this just might be the case: If the config file is used in many places across you app, reading the file multiple times might impact your performance. However, if you choose to use a Singleton, keep in mind the dangers that come with it.

To answer you question, I don't think it's possible to tell what's the best way for you to go, because that depends on your specific app. I can only suggest that you take into account the pros and cons of each option, and making your choice depending on your needs.

Community
  • 1
  • 1
asherbret
  • 5,439
  • 4
  • 38
  • 58
  • This doesn't really answer the OP's question (even your second paragraph just says "there are different ways" without mentioning any of those ways). – Ben Hoyt Nov 03 '16 at 18:47