Debian Codegraph @

flufl/password/_registry.py

raw
1 # Copyright (C) 2011-2014 by Barry A. Warsaw
2 #
3 # This file is part of flufl.password
4 #
5 # flufl.password is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation, version 3 of the License.
8 #
9 # flufl.password is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
12 # License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with flufl.password. If not, see <http://www.gnu.org/licenses/>.
16
17 """Scheme registry."""
18
19 from __future__ import absolute_import, print_function, unicode_literals
20
21 __metaclass__ = type
22 __all__ = [
23 'BadPasswordSchemeError',
24 'lookup',
25 'register',
26 ]
27
28
29 _registry = {}
30
31
32
33 class BadPasswordSchemeError(Exception):
34 """An unknown password scheme tag was given."""
35
36
37
38 def register(scheme_class):
39 """Register a scheme by its tag.
40
41 This is intended to be used as a class descriptor.
42
43 :param scheme_class: A password scheme.
44 :type scheme_class: A class which has a `TAG` attribute. The tag may
45 contain space-separated words with additional information, but the
46 scheme will be registered using the first word as the key.
47 :return: scheme_class
48 """
49 key = scheme_class.TAG.split()[0]
50 _registry[key] = scheme_class
51 return scheme_class
52
53
54 def lookup(tag):
55 """Return a scheme class by its tag.
56
57 :param tag: The tag to search for. The tag may contain space-separated
58 words with additional information, but the scheme will be looked up
59 using the first word as the key.
60 :type tag: string
61 :return: The matching scheme class.
62 :rtype: class
63 :raises BadPasswordSchemeError: when the named scheme can't be found.
64 """
65 key = tag.split()[0]
66 try:
67 return _registry[key]
68 except KeyError:
69 raise BadPasswordSchemeError(tag)