source: package_tags/sipb-xen-www/3.13.1/code/webcommon.py @ 1029

Last change on this file since 1029 was 1001, checked in by broder, 16 years ago

Update (at least some of) the web code to work with newer a SQLAlchemy

File size: 2.1 KB
Line 
1"""Exceptions for the web interface."""
2
3import time
4from invirt import database
5from invirt.database import Machine, MachineAccess
6
7class MyException(Exception):
8    """Base class for my exceptions"""
9    pass
10
11class InvalidInput(MyException):
12    """Exception for user-provided input is invalid but maybe in good faith.
13
14    This would include setting memory to negative (which might be a
15    typo) but not setting an invalid boot CD (which requires bypassing
16    the select box).
17    """
18    def __init__(self, err_field, err_value, expl=None):
19        MyException.__init__(self, expl)
20        self.err_field = err_field
21        self.err_value = err_value
22
23class CodeError(MyException):
24    """Exception for internal errors or bad faith input."""
25    pass
26
27import controls
28
29def cachedproperty(func):
30    name = '__cache_' + func.__name__ + '_' + str(id(func))
31    def getter(self):
32        try:
33            return getattr(self, name)
34        except AttributeError:
35            value = func(self)
36            setattr(self, name, value)
37            return value
38    return property(getter)
39
40class State(object):
41    """State for a request"""
42    def __init__(self, user, isadmin=False):
43        self.username = user
44        self.isadmin = isadmin
45
46    def getMachines(self):
47        if self.isadmin:
48            return Machine.query().join('acl').filter_by(
49                database.or_(MachineAccess.c.user == self.username,
50                             Machine.c.adminable == True))
51        else:
52            return Machine.query().join('acl').filter_by(user=self.username)
53
54    machines = cachedproperty(getMachines)
55    xmlist_raw = cachedproperty(lambda self: controls.getList())
56    xmlist = cachedproperty(lambda self:
57                                dict((m, self.xmlist_raw[m.name])
58                                     for m in self.machines
59                                     if m.name in self.xmlist_raw))
60
61    def clear(self):
62        """Clear the state so future accesses reload it."""
63        for attr in list(self.__dict__):
64            if attr.startswith('__cache_'):
65                delattr(self, attr)
Note: See TracBrowser for help on using the repository browser.