Get conf from envvars

This commit is contained in:
boyska 2015-01-31 22:49:22 +01:00
parent 22bb84d1d4
commit 74579a20a9
No known key found for this signature in database
GPG key ID: 7395DCAE58289CA9
3 changed files with 70 additions and 10 deletions

64
larigira/config.py Normal file
View file

@ -0,0 +1,64 @@
#!/usr/bin/env python
'''
Taken from flask-appconfig
'''
import json
import os
def get_conf(prefix='LARIGIRA_'):
'''This is where everyone should get configuration from'''
conf = {}
conf['CONTINOUS_AUDIODESC'] = dict(kind='mpd', howmany=1)
conf['MPD_HOST'] = os.getenv('MPD_HOST', 'localhost')
conf['MPD_PORT'] = int(os.getenv('MPD_PORT', '6600'))
conf['CACHING_TIME'] = 10
conf['DB_URI'] = 'larigira.db'
conf.update(from_envvars(prefix=prefix))
return conf
def from_envvars(prefix=None, envvars=None, as_json=True):
"""Load environment variables in a dictionary
Values are parsed as JSON. If parsing fails with a ValueError,
values are instead used as verbatim strings.
:param prefix: If ``None`` is passed as envvars, all variables from
``environ`` starting with this prefix are imported. The
prefix is stripped upon import.
:param envvars: A dictionary of mappings of environment-variable-names
to Flask configuration names. If a list is passed
instead, names are mapped 1:1. If ``None``, see prefix
argument.
:param as_json: If False, values will not be parsed as JSON first.
"""
conf = {}
if prefix is None and envvars is None:
raise RuntimeError('Must either give prefix or envvars argument')
# if it's a list, convert to dict
if isinstance(envvars, list):
envvars = {k: None for k in envvars}
if not envvars:
envvars = {k: k[len(prefix):] for k in os.environ.keys()
if k.startswith(prefix)}
for env_name, name in envvars.items():
if name is None:
name = env_name
if env_name not in os.environ:
continue
if as_json:
try:
conf[name] = json.loads(os.environ[env_name])
except ValueError:
conf[name] = os.environ[env_name]
else:
conf[name] = os.environ[env_name]
return conf

View file

@ -3,6 +3,7 @@ import argparse
from pprint import pprint
from .event import EventModel
from .config import get_conf
def main_list(args):
@ -19,8 +20,10 @@ def main_add(args):
def main():
conf = get_conf()
p = argparse.ArgumentParser()
p.add_argument('-f', '--file', help="Filepath for DB", required=True)
p.add_argument('-f', '--file', help="Filepath for DB", required=False,
default=conf['DB_URI'])
sub = p.add_subparsers()
sub_list = sub.add_parser('list')
sub_list.set_defaults(func=main_list)

View file

@ -1,7 +1,6 @@
from __future__ import print_function
from gevent import monkey
monkey.patch_all(subprocess=True)
import os
import logging
FORMAT = '%(asctime)s|%(levelname)s[%(name)s:%(lineno)d] %(message)s'
@ -19,12 +18,7 @@ from eventutils import ParentedLet, Timer
import rpc
from audiogen import audiogenerate
from event import Monitor
conf = {}
conf['CONTINOUS_AUDIODESC'] = dict(kind='mpd', howmany=1)
conf['MPD_HOST'] = os.getenv('MPD_HOST', 'localhost')
conf['MPD_PORT'] = int(os.getenv('MPD_PORT', '6600'))
conf['CACHING_TIME'] = 10
from .config import get_conf
class MpcWatcher(ParentedLet):
@ -107,8 +101,7 @@ def on_player_crash(*args, **kwargs):
def main():
# TODO: update conf from somewhere
conf['DB_URI'] = 'larigira.db'
conf = get_conf()
logging.basicConfig(level=logging.DEBUG)
p = Player(conf)
p.start()