PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/silversupport/disabledapps.py

https://bitbucket.org/ianb/silverlining/
Python | 66 lines | 33 code | 15 blank | 18 comment | 11 complexity | 3dcfb45f9de813bf5c3968baf41fee06 MD5 | raw file
Possible License(s): GPL-2.0
  1. """Routines for managing the list of disabled applications"""
  2. # The file contains application names rather than instance names or locations,
  3. # as what we really care about is databases, and they are shared between
  4. # deployments of the same application.
  5. # The format of the disabled apps file is at present simply a list of
  6. # application names. In the future it might well be desirable to extend this
  7. # with options for the DisabledSite WSGI middleware, such as a list of IPs
  8. # which can be allowed to access the site, or a set of http auth credentials
  9. # which allow access. Happily the file should be empty except in exceptional
  10. # circumstances, and we can therefore just change the data format without
  11. # concern for backwards compatibility.
  12. import os.path
  13. DISABLED_APPS_FILE = '/var/www/disabledapps.txt'
  14. class DisabledSite(object):
  15. """This WSGI app is returned instead of our application when it is disabled
  16. """
  17. def __init__(self, real_app, disabled_app):
  18. self._app = real_app
  19. self._disabled = disabled_app
  20. def __call__(self, environ, start_response):
  21. """Delegates to the disabled app unless some conditions are met"""
  22. if environ.get('silverlining.update'):
  23. return self._app(environ, start_response)
  24. # Allow connections from localhost.
  25. client = environ['REMOTE_ADDR']
  26. if client.strip() in ('localhost', '127.0.0.1'):
  27. return self._app(environ, start_response)
  28. return self._disabled(environ, start_response)
  29. def is_disabled(application_name):
  30. """Return True if the application has been disabled"""
  31. if not os.path.exists(DISABLED_APPS_FILE):
  32. return False
  33. with open(DISABLED_APPS_FILE) as file_:
  34. lines = [line.strip() for line in file_]
  35. return application_name in lines
  36. def disable_application(application_name):
  37. """Adds application_name to the list of disabled applications"""
  38. if not is_disabled(application_name):
  39. with open(DISABLED_APPS_FILE, 'a') as file_:
  40. file_.write(application_name)
  41. file_.write('\n')
  42. def enable_application(application_name):
  43. """Removes application_name from the list of disabled applications"""
  44. lines = []
  45. with open(DISABLED_APPS_FILE, 'r') as file_:
  46. for line in file_:
  47. line = line.strip()
  48. if line != application_name:
  49. lines.append(line)
  50. with open(DISABLED_APPS_FILE, 'w') as file_:
  51. file_.write('\n'.join(lines))