| 1 |
from collections import OrderedDict |
| 2 |
import inspect |
| 3 |
import operator |
| 4 |
|
| 5 |
import importlib |
| 6 |
|
| 7 |
|
| 8 |
class DoesNotExist(ValueError): |
| 9 |
pass |
| 10 |
|
| 11 |
|
| 12 |
class MultipleObjectsReturned(ValueError): |
| 13 |
pass |
| 14 |
|
| 15 |
|
| 16 |
class QuerySet(object): |
| 17 |
def __init__(self, values): |
| 18 |
self.values = list(values) |
| 19 |
|
| 20 |
def __iter__(self): |
| 21 |
for value in self.values: |
| 22 |
yield value |
| 23 |
|
| 24 |
def __len__(self): |
| 25 |
return len(self.values) |
| 26 |
|
| 27 |
def __repr__(self): |
| 28 |
return "<{0}: {1}>".format(self.__class__.__name__, str(list(self.values))) |
| 29 |
|
| 30 |
def __getitem__(self, i): |
| 31 |
return self.values[i] |
| 32 |
|
| 33 |
def __eq__(self, other): |
| 34 |
return self.values == list(other) |
| 35 |
|
| 36 |
def _clone(self, new_values): |
| 37 |
return self.__class__(new_values) |
| 38 |
|
| 39 |
def _build_filter(self, **kwargs): |
| 40 |
"""build a single filter function used to match arbitrary object""" |
| 41 |
|
| 42 |
def object_filter(obj): |
| 43 |
for key, value in kwargs.items(): |
| 44 |
# we replace dango-like lookup by dots, so attrgetter can do his job |
| 45 |
key = key.replace("__", ".") |
| 46 |
|
| 47 |
getter = operator.attrgetter(key) |
| 48 |
if not getter(obj) == value: |
| 49 |
return False |
| 50 |
return True |
| 51 |
|
| 52 |
return object_filter |
| 53 |
|
| 54 |
def exists(self): |
| 55 |
return len(self) > 0 |
| 56 |
|
| 57 |
def order_by(self, key): |
| 58 |
reverse = False |
| 59 |
if key.startswith("-"): |
| 60 |
reverse = True |
| 61 |
key = key[1:] |
| 62 |
|
| 63 |
return self._clone( |
| 64 |
sorted(self.values, key=operator.attrgetter(key), reverse=reverse) |
| 65 |
) |
| 66 |
|
| 67 |
def all(self): |
| 68 |
return self._clone(self.values) |
| 69 |
|
| 70 |
def count(self): |
| 71 |
return len(self) |
| 72 |
|
| 73 |
def first(self): |
| 74 |
try: |
| 75 |
return self.values[0] |
| 76 |
except IndexError: |
| 77 |
return None |
| 78 |
|
| 79 |
def last(self): |
| 80 |
try: |
| 81 |
return self.values[-1] |
| 82 |
except IndexError: |
| 83 |
return None |
| 84 |
|
| 85 |
def filter(self, **kwargs): |
| 86 |
_filter = self._build_filter(**kwargs) |
| 87 |
return self._clone(filter(_filter, self.values)) |
| 88 |
|
| 89 |
def exclude(self, **kwargs): |
| 90 |
_filter = self._build_filter(**kwargs) |
| 91 |
return self._clone(filter(lambda v: not _filter(v), self.values)) |
| 92 |
|
| 93 |
def get(self, **kwargs): |
| 94 |
|
| 95 |
matches = self.filter(**kwargs) |
| 96 |
if len(matches) == 0: |
| 97 |
raise DoesNotExist() |
| 98 |
if len(matches) > 1: |
| 99 |
raise MultipleObjectsReturned() |
| 100 |
return matches[0] |
| 101 |
|
| 102 |
|
| 103 |
class Manager(object): |
| 104 |
"""Used to retrieve / order / filter preferences pretty much as django's ORM managers""" |
| 105 |
|
| 106 |
def __init__(self, registry, queryset_class): |
| 107 |
self.registry = registry |
| 108 |
self.queryset_class = queryset_class |
| 109 |
|
| 110 |
def get_queryset(self): |
| 111 |
return self.queryset_class(self.registry.values()) |
| 112 |
|
| 113 |
def all(self): |
| 114 |
return self.get_queryset().all() |
| 115 |
|
| 116 |
def __getattr__(self, attr): |
| 117 |
try: |
| 118 |
return super().__getattr__(attr) |
| 119 |
except AttributeError: |
| 120 |
# Try to proxy on queryset if possible |
| 121 |
return getattr(self.get_queryset(), attr) |
| 122 |
|
| 123 |
|
| 124 |
class Registry(OrderedDict): |
| 125 |
manager_class = Manager |
| 126 |
queryset_class = QuerySet |
| 127 |
|
| 128 |
def __init__(self, *args, **kwargs): |
| 129 |
super().__init__(*args, **kwargs) |
| 130 |
self.objects = self.manager_class(self, self.queryset_class) |
| 131 |
|
| 132 |
def register_decorator_factory(self, **kwargs): |
| 133 |
""" |
| 134 |
Return an actual decorator for registering objects into registry |
| 135 |
""" |
| 136 |
name = kwargs.get("name") |
| 137 |
|
| 138 |
def decorator(decorated): |
| 139 |
self.register_func(data=decorated, name=name) |
| 140 |
return decorated |
| 141 |
|
| 142 |
return decorator |
| 143 |
|
| 144 |
def register(self, data=None, name=None, **kwargs): |
| 145 |
""" |
| 146 |
Use this method as a decorator on class/function you want to register: |
| 147 |
|
| 148 |
@registry.register(name="test") |
| 149 |
class Test: |
| 150 |
pass |
| 151 |
|
| 152 |
:param:data: Something to register in the registry |
| 153 |
:param:name: The unique name that will identify registered data. |
| 154 |
If None, by default, registry will try to deduce name from class name (if object is a class or an object). |
| 155 |
You can change this behaviour by overriding :py::method:`prepare_name` |
| 156 |
|
| 157 |
""" |
| 158 |
if data is None: |
| 159 |
return self.register_decorator_factory(data=data, name=name, **kwargs) |
| 160 |
else: |
| 161 |
self.register_func(data=data, name=name, **kwargs) |
| 162 |
return data |
| 163 |
|
| 164 |
def get_object_name(self, data): |
| 165 |
""" |
| 166 |
Return a name from an element (object, class, function...) |
| 167 |
""" |
| 168 |
if callable(data): |
| 169 |
return data.__name__ |
| 170 |
|
| 171 |
elif inspect.isclass(data): |
| 172 |
return data.__class__.__name__ |
| 173 |
|
| 174 |
else: |
| 175 |
raise ValueError( |
| 176 |
"Cannot deduce name from given object ({0}). Please user registry.register() with a 'name' argument.".format( |
| 177 |
data |
| 178 |
) |
| 179 |
) |
| 180 |
|
| 181 |
def validate(self, data): |
| 182 |
""" |
| 183 |
Called before registering a new value into the registry |
| 184 |
Override this method if you want to restrict what type of data cna be registered |
| 185 |
""" |
| 186 |
return True |
| 187 |
|
| 188 |
def prepare_name(self, data, name=None): |
| 189 |
if name is None: |
| 190 |
return self.get_object_name(data) |
| 191 |
return name |
| 192 |
|
| 193 |
def register_func(self, data, name=None, **kwargs): |
| 194 |
""" |
| 195 |
Register abritrary data into the registry |
| 196 |
""" |
| 197 |
if self.validate(data): |
| 198 |
o = self.prepare_data(data) |
| 199 |
n = self.prepare_name(data, name) |
| 200 |
self[n] = o |
| 201 |
self.post_register(data=0, name=n) |
| 202 |
else: |
| 203 |
raise ValueError( |
| 204 |
"{0} (type: {0.__class__}) is not a valid value for {1} registry".format( |
| 205 |
data, self.__class__ |
| 206 |
) |
| 207 |
) |
| 208 |
|
| 209 |
def post_register(self, data, name): |
| 210 |
""" |
| 211 |
Will be triggered each time a new element is successfully registered. |
| 212 |
Feel free to override this method |
| 213 |
""" |
| 214 |
pass |
| 215 |
|
| 216 |
def prepare_data(self, data): |
| 217 |
""" |
| 218 |
Override this methode if you want to manipulate data before registering it |
| 219 |
You MUST return a value to register |
| 220 |
""" |
| 221 |
return data |
| 222 |
|
| 223 |
def autodiscover(self, apps, force_reload=False): |
| 224 |
""" |
| 225 |
Iterate throught every installed apps, trying to import `look_into` package |
| 226 |
:param apps: an iterable of string, refering to python modules the registry will try to import via autodiscover |
| 227 |
""" |
| 228 |
for app in apps: |
| 229 |
app_package = __import__(app) |
| 230 |
try: |
| 231 |
|
| 232 |
package = "{0}.{1}".format( |
| 233 |
app, self.look_into |
| 234 |
) # try to import self.package inside current app |
| 235 |
# print(package) |
| 236 |
module = __import__(package) |
| 237 |
if force_reload: |
| 238 |
importlib.reload(module) |
| 239 |
except ImportError as exc: |
| 240 |
# From django's syncdb |
| 241 |
# This is slightly hackish. We want to ignore ImportErrors |
| 242 |
# if the module itself is missing -- but we don't |
| 243 |
# want to ignore the exception if the module exists |
| 244 |
# but raises an ImportError for some reason. The only way we |
| 245 |
# can do this is to check the text of the exception. Note that |
| 246 |
# we're a bit broad in how we check the text, because different |
| 247 |
# Python implementations may not use the same text. |
| 248 |
# CPython uses the text "No module named" |
| 249 |
# PyPy uses "No module named myproject.myapp" |
| 250 |
msg = exc.args[0] |
| 251 |
if not msg.startswith("No module named") or self.look_into not in msg: |
| 252 |
raise |
| 253 |
|
| 254 |
|
| 255 |
class MetaRegistry(Registry): |
| 256 |
""" |
| 257 |
Keep a reference to all registries |
| 258 |
""" |
| 259 |
|
| 260 |
look_into = "registries" |
| 261 |
|
| 262 |
def autodiscover(self, apps, cascade=True, **kwargs): |
| 263 |
""" |
| 264 |
:param cascade: If true, will trigger autodiscover on discovered registries |
| 265 |
""" |
| 266 |
super().autodiscover(apps, **kwargs) |
| 267 |
if cascade: |
| 268 |
self.autodiscover_registries(apps) |
| 269 |
|
| 270 |
def autodiscover_registries(self, apps): |
| 271 |
for key, registry in self.items(): |
| 272 |
registry.autodiscover(apps) |
| 273 |
|
| 274 |
|
| 275 |
meta_registry = MetaRegistry() |