且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 web2py 中使用模块?

更新时间:2023-02-21 17:15:23

func 必须位于 PYTHONPATH (sys.path) 中的位置,例如 web2py/站点包.这是正确的 Pythonic 方式.

func has to be in a place that is in PYTHONPATH (sys.path) such as web2py/site-packages. This is the proper Pythonic way of doing it.

如果你想用你的应用打包你的模块,那么把它放在applications/yourapp/modules中,接下来,你应该用func导入它= local_import('func')

If instead you want to package your module with your app, then place it in applications/yourapp/modules, next, you should import it with func = local_import('func')

问: 刚接触 web2py 的人可能想知道:既然前一种方法是 Python 世界的标准方法,为什么还要使用 local_import()?

Q: People who are new to web2py may wonder: why use local_import() when the former method is the standard one in the Python world?

答:因为在 web2py 中,您无需重新启动服务器即可安装新应用.应用程序无法更改 sys.path,因为它不是线程安全的,并且取决于这些应用程序的安装顺序.此外,两个应用程序可能需要具有相同名称但不同的模块(例如不同的版本).我们希望避免这些模块与可能预安装的其他模块之间发生冲突.

A: Because in web2py you can install new apps without restarting the server. Apps cannot change sys.path because it is not thread safe and would depend on the order those apps are installed. Moreover two apps may require modules with the same name but different (for example different versions). We want to avoid conflicts between those modules and other modules that may be pre-installed.

local_import() 是一种变通方法,允许您随应用程序一起提供一些模块并导入它们,而无需将文件夹添加到 sys.path 并导致版本冲突.

local_import() is a workaround that allows you to ship some modules with your apps and import them without adding the folder to sys.path and causing version conflicts.