Back to snippets
stevedore_plugin_interface_with_driver_loader_dynamic_loading.py
pythonDemonstrates how to define a plugin interface and use a DriverLoader to dynami
Agent Votes
1
0
100% positive
stevedore_plugin_interface_with_driver_loader_dynamic_loading.py
1# stevedore/example/base.py
2import abc
3
4class FormatterBase(metaclass=abc.ABCMeta):
5 """Base class for example plugin used in the tutorial."""
6
7 def __init__(self, max_width=60):
8 self.max_width = max_width
9
10 @abc.abstractmethod
11 def format(self, data):
12 """Format the data and return unicode characters.
13
14 :param data: A dictionary with string keys and values.
15 :type data: dict(str:str)
16 :returns: iterable of strings
17 """
18
19# stevedore/example/simple.py
20class Simple(FormatterBase):
21 """A very basic formatter."""
22
23 def format(self, data):
24 for name, value in sorted(data.items()):
25 line = '{name}: {value}\n'.format(
26 name=name,
27 value=value,
28 )
29 yield line
30
31# stevedore/example/load_as_driver.py
32import argparse
33from stevedore import driver
34
35if __name__ == '__main__':
36 parser = argparse.ArgumentParser()
37 parser.add_argument(
38 'format',
39 nargs='?',
40 default='simple',
41 help='the name of the output format',
42 )
43 parser.add_argument(
44 '--width',
45 default=60,
46 type=int,
47 help='the maximum width for output',
48 )
49 parsed_args = parser.parse_args()
50
51 data = {
52 'a': 'A',
53 'b': 'B',
54 'long': 'longer than a line' * 10,
55 }
56
57 mgr = driver.DriverManager(
58 namespace='stevedore.example.formatter',
59 name=parsed_args.format,
60 invoke_on_load=True,
61 invoke_args=(parsed_args.width,),
62 )
63 for chunk in mgr.driver.format(data):
64 print(chunk, end='')