2015-11-16 50 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中存儲傳統的列表和字符串,但是你可以很容易地訪問腳本中定義的函數。

相關問題