2015-11-16 51 views
-1

我使用Python类型的字典映射功能:我可以将Python函数存储在MongoDB集合上吗?

def linear(a, x, b): 
    return a * x + b 


def quadratic(a, x, b, c): 
    return a * x * x + b * x + c 


sensor = { 
    'id': 'aaaaa', 
    'name': 'temp001', 
    'quantity': 'temperature', 
    'unit': 'C', 
    'charlength': 4, 
    'convert': { 
     'linear': linear(3, 2, 6), 
     'quadratic': quadratic(2, 4, 7, 8) 
    } 
} 

但是当我使用MongoDB的存储上收集的字典,我得到的是只是一个字符串,而不是一个函数调用的结果。

我该如何转换它?我读过使用execeval是不是很安全?

+0

你会期望结果是什么?你会做什么/如果你可以存储“函数调用”,你想如何处理数据? – deceze

+0

@deceze现在,当我迭代字典时,我可以通过.itervalues()方法调用函数。我也想这样做。 – Hugo

+1

@Hugo你不是在dict中存储函数,而是将结果存储在dict中。 – Netwave

回答

2

你可以这样做:

sensor = { 
    'id': 'aaaaa', 
    'name': 'temp001', 
    'quantity': 'temperature', 
    'unit': 'C', 
    'charlength': 4, 
    'convert': { 
     'linear': ("linear", 3, 2, 6), 
     'quadratic': ("quadratic", 2, 4, 7, 8) 
    } 
} 

检索时,你可以这样做:

linear_function = sensor["convert"]["linear"] 

globals()[linear_function[0]](*linear_function[1:]) 

,并通过一个字符串参数,而不是使用eval()这是纯风险访问功能。

,并使其更小矮胖的,因为你已经存储的功能名称作为关键字,你可以这样做:

sensor = { 
    'id': 'aaaaa', 
    'name': 'temp001', 
    'quantity': 'temperature', 
    'unit': 'C', 
    'charlength': 4, 
    'convert': { 
     'linear': (3, 2, 6), 
     'quadratic': (2, 4, 7, 8) 
    } 
} 

linear_function_parameters = sensor["convert"]["linear"] 
globals()["linear"](*linear_function_parameters) 

甚至

for function in sensor['convert']: 
    variables = sensor['convert'][function] 
    result = globals()[function](*variables) 

这将完全使它动态。 这样你只需要在MongoDB中存储传统的列表和字符串,但是你可以很容易地访问脚本中定义的函数。

相关问题