config.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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['FILE_PATH_SUGGESTION'] = () # tuple of paths
  28. conf.update(from_envvars(prefix=prefix))
  29. return conf
  30. def from_envvars(prefix=None, envvars=None, as_json=True):
  31. """Load environment variables in a dictionary
  32. Values are parsed as JSON. If parsing fails with a ValueError,
  33. values are instead used as verbatim strings.
  34. :param prefix: If ``None`` is passed as envvars, all variables from
  35. ``environ`` starting with this prefix are imported. The
  36. prefix is stripped upon import.
  37. :param envvars: A dictionary of mappings of environment-variable-names
  38. to Flask configuration names. If a list is passed
  39. instead, names are mapped 1:1. If ``None``, see prefix
  40. argument.
  41. :param as_json: If False, values will not be parsed as JSON first.
  42. """
  43. conf = {}
  44. if prefix is None and envvars is None:
  45. raise RuntimeError('Must either give prefix or envvars argument')
  46. # if it's a list, convert to dict
  47. if isinstance(envvars, list):
  48. envvars = {k: None for k in envvars}
  49. if not envvars:
  50. envvars = {k: k[len(prefix):] for k in os.environ.keys()
  51. if k.startswith(prefix)}
  52. for env_name, name in envvars.items():
  53. if name is None:
  54. name = env_name
  55. if env_name not in os.environ:
  56. continue
  57. if as_json:
  58. try:
  59. conf[name] = json.loads(os.environ[env_name])
  60. except ValueError:
  61. conf[name] = os.environ[env_name]
  62. else:
  63. conf[name] = os.environ[env_name]
  64. return conf