通过 API 发送函数实例 (django)

sending a function instance over API (django)

可能是个愚蠢的问题:) 我有两个 Django 应用程序, 我需要其中一个来使用另一个的功能而不导入它们。 就好像我正在使用 API 请求他们一样,有没有办法我可以获得一个函数的实例并使用它,我不想执行以下操作:

response = requests.get('HTTP://URL/example/', data)
data = response.json()

我想做这样的事情

function = requests.get('HTTP://URL/example/')

并执行函数如下

data = function()

谢谢

可以使用marshal模块序列化函数代码,添加为请求内容,在其他应用中反序列化。

In [13]: def foo(a, b):
   print a + b
  ....:

In [14]: import marshal

In [15]: a = marshal.dumps(foo.func_code)

In [16]: a

Out[16]:
'c\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00C\x00\x00\x00s\r\x00\x00\x00|\x00\x00|\x01\x00\x17GHd\x00\x00S(\x01\x00\x00\x00N(\x00\x00\x00\x00(\x02\x00\x00\x00t\x01\x00\x00\x00at\x01\x00\x00\x00b(\x00\x00\x00\x00(\x00\x00\x00\x00s\x1f\x00\x00\x00<ipython-input-13-a0f238eac2f8>t\x03\x00\x00\x00foo\x01\x00\x00\x00s\x02\x00\x00\x00\x00\x01'

另一位口译员:

In [13]: import marshal, types

In [14]: a = marshal.loads('c\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00C\x00\x00\x00s\r\x00\x00\x00|\x00\x00|\x01\x00\x17GHd\x00\x00S(\x01\x00\x00\x00N(\x00\x00\x00\x00(\x02\x00\x00\x00t\x01\x00\x00\x00at\x01\x00\x00\x00b(\x00\x00\x00\x00(\x00\x00\x00\x00s\x1e\x00\x00\x00<ipython-input-1-a0f238eac2f8>t\x03\x00\x00\x00foo\x01\x00\x00\x00s\x02\x00\x00\x00\x00\x01')

In [15]: types.FunctionType(a, globals(), 'foo')(1, 2)
3

但是您需要确保在执行之前没有人会向您发送恶意代码。另请注意,您将无法访问函数原始模块中定义的任何全局变量。

一般来说我不会推荐这种方法。最好只使用 RestAPI 来获得你想要的结果,而不是传递函数。