PageRenderTime 122ms CodeModel.GetById 60ms app.highlight 5ms RepoModel.GetById 56ms app.codeStats 0ms

/silversupport/disabledapps.py

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