我如何在web2py中使用模块? [英] How can I use modules in web2py?

查看:155
本文介绍了我如何在web2py中使用模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 func.py 中有一些函数,我想从我的web2py控制器访问 default.py 。我尝试导入并使用import func和calculateomething = func在 default.py 中导入和使用 func.py 计算某物,但它不起作用。文件 func.py 也会添加到我的web2py程序的Modules部分。



为什么它不起作用?我怎样才能使它工作?模块应该位于 func.py 还是 default / func.py 或其他?

解决方案

func 必须位于 PYTHONPATH (sys.path),比如 web2py / site-packages 。如果您希望将您的模块与您的应用程序一起打包,请将它放在<$ em>中。

c $ c> applications / yourapp / modules ,接下来,您应该使用 func = local_import('func')

导入它。 b
$ b

问:刚接触web2py的人可能会疑惑:为什么当前一种方法使用 local_import()时是Python世界的标准吗?



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

local_import()是一种解决方法,允许您在应用中发布一些模块,并导入它们而不会将文件夹添加到 sys.path 并导致版本冲突。


I have some functions in func.py that I would like to access from my web2py controller called default.py. I tried to import and use func.py in default.py with "import func" and "calculatesomething = func.calculatesomething", but it doesn't work. The file func.py is also added in the Modules section of my web2py program.

Why it is not working? How can I make it to work? Should the module be in func.py or default/func.py or something else?

解决方案

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.

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')

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?

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() 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.

这篇关于我如何在web2py中使用模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆