Python simple plugin system prototype


記錄一下之前用 Python 實現的一個簡單 Plugin 原型.
想實現類 WordPress 的結構.
更完整的版本還在實現中請留意 Github 上存檔.
目前這版本用的是 class method 實現感覺不太好.

1
2
3
4
5
> python test.py

Content: This is test message
Encoded: VGhpcyBpcyB0ZXN0IG1lc3NhZ2U=
Decoded: This is test message

Path: ./test.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
#coding: utf-8

from os.path import join, abspath, dirname
from plugin import Plugin

def main():
Plugin.folder(join(abspath(dirname(__file__)), 'plugins'))

content = 'This is test message'
encoded = Plugin.apply_filter('encode', content)
decoded = Plugin.apply_filter('decode', encoded)

Plugin.do_action('result', dict(
content = content,
encoded = encoded,
decoded = decoded,
))

if __name__ == "__main__":
main()

Path: ./plugin.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python
#coding: utf-8

import os
import imp
import sys

class Plugin(object):

filters = {}
actions = {}

@classmethod
def folder(cls, path, module_name='pp.plugins'):
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

parent_module = imp.new_module(module_name)
sys.modules[module_name] = parent_module

for folder_path, folder_names, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.py'):
file_path = os.path.join(folder_path, filename)
source_name = "{0}.{1}".format(module_name, filename.replace('.py', ''))

imp.load_source(source_name, file_path)

@classmethod
def add_filter(cls, name, method):
cls.filters[name] = method

@classmethod
def apply_filter(cls, name, value):
filter = cls.filters.get(name)

if not filter:
raise ValueError('Can not found filter named: {0}'.format(name))
else:
return filter(value)

@classmethod
def add_action(cls, name, method):
cls.actions[name] = method

@classmethod
def do_action(cls, name, value):
action = cls.actions.get(name)

if not action:
raise ValueError('Can not found action named: {0}'.format(name))
else:
action(value)

Path: ./plugins/hello/secret.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from base64 import b64decode, b64encode
from plugin import Plugin

# Filter
def encode(content):
return b64encode(content)

def decode(content):
return b64decode(content)

Plugin.add_filter('encode', encode)
Plugin.add_filter('decode', decode)

# Action
def result(results):
print("Content: {0}".format(results.get('content')))
print("Encoded: {0}".format(results.get('encoded')))
print("Decoded: {0}".format(results.get('decoded')))

Plugin.add_action('result', result)