config.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. '''
  3. Taken from flask-appconfig
  4. '''
  5. import json
  6. import os
  7. from xdg import BaseDirectory
  8. def get_conf(prefix='LARIGIRA_'):
  9. '''This is where everyone should get configuration from'''
  10. conf_dir = BaseDirectory.save_config_path('larigira')
  11. conf = {}
  12. conf['CONTINOUS_AUDIOSPEC'] = dict(kind='mpd', howmany=1)
  13. conf['MPD_HOST'] = os.getenv('MPD_HOST', 'localhost')
  14. conf['MPD_PORT'] = int(os.getenv('MPD_PORT', '6600'))
  15. conf['CACHING_TIME'] = 10
  16. conf['DB_URI'] = os.path.join(conf_dir, 'db.json')
  17. conf['SCRIPTS_PATH'] = os.path.join(conf_dir, 'scripts')
  18. conf['BOOTSTRAP_SERVE_LOCAL'] = True
  19. conf['SECRET_KEY'] = 'Please replace me!'
  20. conf['MPD_WAIT_START'] = True
  21. conf['MPD_WAIT_START_RETRYSECS'] = 5
  22. conf['CHECK_SECS'] = 20 # period for checking playlist length
  23. conf['EVENT_TICK_SECS'] = 30 # period for scheduling events
  24. conf['DEBUG'] = False
  25. conf['LOG_CONFIG'] = False
  26. conf['TMPDIR'] = os.getenv('TMPDIR', '/tmp/')
  27. conf.update(from_envvars(prefix=prefix))
  28. return conf
  29. def from_envvars(prefix=None, envvars=None, as_json=True):
  30. """Load environment variables in a dictionary
  31. Values are parsed as JSON. If parsing fails with a ValueError,
  32. values are instead used as verbatim strings.
  33. :param prefix: If ``None`` is passed as envvars, all variables from
  34. ``environ`` starting with this prefix are imported. The
  35. prefix is stripped upon import.
  36. :param envvars: A dictionary of mappings of environment-variable-names
  37. to Flask configuration names. If a list is passed
  38. instead, names are mapped 1:1. If ``None``, see prefix
  39. argument.
  40. :param as_json: If False, values will not be parsed as JSON first.
  41. """
  42. conf = {}
  43. if prefix is None and envvars is None:
  44. raise RuntimeError('Must either give prefix or envvars argument')
  45. # if it's a list, convert to dict
  46. if isinstance(envvars, list):
  47. envvars = {k: None for k in envvars}
  48. if not envvars:
  49. envvars = {k: k[len(prefix):] for k in os.environ.keys()
  50. if k.startswith(prefix)}
  51. for env_name, name in envvars.items():
  52. if name is None:
  53. name = env_name
  54. if env_name not in os.environ:
  55. continue
  56. if as_json:
  57. try:
  58. conf[name] = json.loads(os.environ[env_name])
  59. except ValueError:
  60. conf[name] = os.environ[env_name]
  61. else:
  62. conf[name] = os.environ[env_name]
  63. return conf