Flask:将自定义函数导入 API
Flask: importing custom functions into API
我有 R 背景,我正在尝试使用 Flask 在 Python 中开发一个 API。我的文件夹看起来像这样:
project
--server.py
--custom_functions
----func1.py
----func2.py
--more_custom_functions
----subfolder1
------func3.py
------func4.py
----subfolder2
------func5.py
------func6.py
我更喜欢根据用途将我的自定义功能组织到不同的子文件夹中,因此 custom_functions 可以是与清洁等相关的功能。理想情况下,当我启动 server.py 使用(在 Windows CMD 中,如果有帮助的话)
python server.py
在目录 /project 中,我希望能够导入每个函数。函数看起来像
import numpy as np
def func1 (x) :
return(x + 1)
仅此而已。
我的问题是:服务器初始化时(即 python server.py
时)如何导入每个模块(例如 numpy/ pandas) 全局以便所有子函数都可以使用这些模块而无需在其中调用导入,即(在上面的示例中,我们可以删除 import numpy as np
),并导入所有函数 func1
、func2
、...、func6
?我不介意我是否必须将它们称为 custom_functions.func1
或 more_custom_functions.subfolder1.func3
,比如说,如果需要的话。
我尝试了很多方法,例如将 __init__.py
放入某些文件夹并将 __all__ = ["func1", "func2"]
添加到此文件(以及将其留空)。我也试过
import sys, os
sys.path.append(os.getcwd() + '\custom_functions')
import custom_functions
以及类似 from custom_functions import * 的变体,都无济于事。
我遇到的一些错误涉及:
module 'custom_functions' has no attribute func1
,或
name 'custom_functions' is not defined
。
在 R 中,我会使用类似 source(dir, recursive=TRUE, pattern="*.R")
的内容,然后 library/require 在代码的最开始使用所有包,一切都很好。有一个简单的等价物吗?或者我是否必须将每个函数移动到一个文件中(比如 functions.py)然后导入函数?
感谢您的帮助。
似乎有一个或多或少适合我的需要的中间解决方案,即使它在 Python 方面可能不是最佳实践。
import os
import glob
files_names = glob.glob(os.getcwd() + '\custom_functions\**\*.py')
for f in file_names : exec(open(f).read())
这让我可以使用自定义函数而无需将它们作为模块调用,即我可以像
一样使用它们
func1()
而不是
custom_functions.func1()
我有 R 背景,我正在尝试使用 Flask 在 Python 中开发一个 API。我的文件夹看起来像这样:
project
--server.py
--custom_functions
----func1.py
----func2.py
--more_custom_functions
----subfolder1
------func3.py
------func4.py
----subfolder2
------func5.py
------func6.py
我更喜欢根据用途将我的自定义功能组织到不同的子文件夹中,因此 custom_functions 可以是与清洁等相关的功能。理想情况下,当我启动 server.py 使用(在 Windows CMD 中,如果有帮助的话)
python server.py
在目录 /project 中,我希望能够导入每个函数。函数看起来像
import numpy as np
def func1 (x) :
return(x + 1)
仅此而已。
我的问题是:服务器初始化时(即 python server.py
时)如何导入每个模块(例如 numpy/ pandas) 全局以便所有子函数都可以使用这些模块而无需在其中调用导入,即(在上面的示例中,我们可以删除 import numpy as np
),并导入所有函数 func1
、func2
、...、func6
?我不介意我是否必须将它们称为 custom_functions.func1
或 more_custom_functions.subfolder1.func3
,比如说,如果需要的话。
我尝试了很多方法,例如将 __init__.py
放入某些文件夹并将 __all__ = ["func1", "func2"]
添加到此文件(以及将其留空)。我也试过
import sys, os
sys.path.append(os.getcwd() + '\custom_functions')
import custom_functions
以及类似 from custom_functions import * 的变体,都无济于事。
我遇到的一些错误涉及:
module 'custom_functions' has no attribute func1
,或
name 'custom_functions' is not defined
。
在 R 中,我会使用类似 source(dir, recursive=TRUE, pattern="*.R")
的内容,然后 library/require 在代码的最开始使用所有包,一切都很好。有一个简单的等价物吗?或者我是否必须将每个函数移动到一个文件中(比如 functions.py)然后导入函数?
感谢您的帮助。
似乎有一个或多或少适合我的需要的中间解决方案,即使它在 Python 方面可能不是最佳实践。
import os
import glob
files_names = glob.glob(os.getcwd() + '\custom_functions\**\*.py')
for f in file_names : exec(open(f).read())
这让我可以使用自定义函数而无需将它们作为模块调用,即我可以像
一样使用它们func1()
而不是
custom_functions.func1()