source: trunk/packages/sipb-xen-www/code/webcommon.py @ 1001

Last change on this file since 1001 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
RevLine 
[209]1"""Exceptions for the web interface."""
2
[535]3import time
[874]4from invirt import database
[864]5from invirt.database import Machine, MachineAccess
[209]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
[261]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
[572]40class State(object):
41    """State for a request"""
[867]42    def __init__(self, user, isadmin=False):
[572]43        self.username = user
[867]44        self.isadmin = isadmin
[209]45
[632]46    def getMachines(self):
[867]47        if self.isadmin:
[1001]48            return Machine.query().join('acl').filter_by(
[874]49                database.or_(MachineAccess.c.user == self.username,
50                             Machine.c.adminable == True))
[632]51        else:
[1001]52            return Machine.query().join('acl').filter_by(user=self.username)
[632]53
54    machines = cachedproperty(getMachines)
[554]55    xmlist_raw = cachedproperty(lambda self: controls.getList())
[535]56    xmlist = cachedproperty(lambda self:
[554]57                                dict((m, self.xmlist_raw[m.name])
58                                     for m in self.machines
59                                     if m.name in self.xmlist_raw))
[535]60
[209]61    def clear(self):
62        """Clear the state so future accesses reload it."""
[264]63        for attr in list(self.__dict__):
[261]64            if attr.startswith('__cache_'):
[209]65                delattr(self, attr)
Note: See TracBrowser for help on using the repository browser.