python 从字符串格式的模块与方法中,获取相应的模块和方法对

2018-05-06  本文已影响16人  ugvibib

目的:

从前端获取模块和方法的名称,后台搜索到该方法后,执行,并将结果返回到前端。

实现:
目录结构:


image.png

test.config.py 内容:

def run_method(key, value):
    print('执行方法成功!')
    return str(key)+'__'+str(value)

例如:从前端获取的模块和方法格式如下:

url='config|run_method'

对字符串进行处理,得到模块对象、方法对象、方法的入参,如下:

import re
import inspect

# myMain.py

def search_method(url='config|run_method'):
    module, method = url.strip().split('|')
    print(module, method)
    parent_module = __import__('test.' + module)
    module = getattr(parent_module, module)
    method_args = inspect.signature(method)
    return method_args
# (key, value)

剩下的部分就是:把入参给前端生成input,用户输入,后台获取后执行。

ok!

上一篇 下一篇

猜你喜欢

热点阅读