如何在Google App Engine中导入模块? [英] How to import modules in Google App Engine?
问题描述
我创建了一个基于默认模板的简单GAE应用程序。我想添加一个外部模块,如 short_url 。我该怎么做呢?我发现迄今为止的方向是令人困惑的,GAE似乎并没有使用PYTHONPATH,我想这是显而易见的原因。
I have created a simple GAE app based on the default template. I want to add an external module like short_url. How do I do this? The directions that I have found so far are confusing and GAE doesn't seem to use PYTHONPATH for obvious reasons I guess.
推荐答案
只需将 short_url.py
文件放入您的应用程序目录即可。
Simply place the short_url.py
file in your app's directory.
示例App Engine项目:
Sample App Engine project:
myapp/
app.yaml
index.yaml
main.py
short_url.py
views.py
并且在 views.py
(或任何地方)中,您然后可以像这样导入:
And in views.py
(or wherever), you can then import like so:
import short_url
对于更复杂的项目,或许更好的方法是创建一个专门用于依赖关系的目录;比如 lib
:
myapp/
lib/
__init__.py
short_url.py
app.yaml
index.yaml
main.py
views.py
from lib import short_url
< hr>
编辑#2:
道歉,我应该早一点提及。您需要修改您的路径,感谢Nick Johnson进行以下修复。
确保在启动应用程序之前运行此代码;像这样:
Edit #2:
Apologies, I should have mentioned this earlier. You need modify your path, thanks to Nick Johnson for the following fix.
Ensure that this code is run before starting up your app; something like this:
import os
import sys
def fix_path():
# credit: Nick Johnson of Google
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
def main():
url_map = [ ('/', views.IndexHandler),] # etc.
app = webapp.WSGIApplication(url_map, debug=False)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
fix_path()
main()
编辑3:
要让此代码在所有其他导入之前运行,您可以将在你的应用程序的基本目录中(Python可以识别该目录中的所有内容,而不需要修改任何路径)管理它自己的文件中的代码。
然后你只需确保导入
To get this code to run before all other imports, you can put the path managing code in a file of its own in your app's base directory (Python recognizes everything in that directory without any path modifications).
And then you'd just ensure that this import
import fix_path
..在 main.py
文件中的所有其他导入之前列出。
这是
...is listed before all other imports in your main.py
file.
Here's a link to full, working example in case my explanation wasn't clear.
这篇关于如何在Google App Engine中导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!