source: trunk/packages/invirt-web/code/webcommon.py @ 1509

Last change on this file since 1509 was 1318, checked in by price, 16 years ago

sipb-xen-www -> invirt-web

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:
[1169]48            return Machine.query().join('acl').filter(
49                database.or_(MachineAccess.user==self.username,
50                             Machine.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.