问题描述
我已经基于默认模板创建了一个简单的 GAE 应用程序.我想添加一个像 short_url 这样的外部模块.我该怎么做呢?到目前为止,我发现的方向令人困惑,我猜出于显而易见的原因,GAE 似乎没有使用 PYTHONPATH.
只需将 short_url.py
文件放在您的应用程序目录中即可.
示例 App Engine 项目:
我的应用程序/应用程序.yaml索引.yaml主文件短网址.py视图.py然后在 views.py
(或任何地方)中,您可以像这样导入:
import short_url
对于更复杂的项目,也许更好的方法是专门为依赖创建一个目录;说lib
:
from lib import short_url
编辑#2:
抱歉,我应该早点提到这一点.您需要修改您的路径,感谢尼克约翰逊的以下修复.
确保在启动应用程序之前运行此代码;像这样:
导入操作系统导入系统def fix_path():# 信用:谷歌的尼克约翰逊sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))定义主():url_map = [ ('/', views.IndexHandler),] # 等.app = webapp.WSGIApplication(url_map, debug=False)wsgiref.handlers.CGIHandler().run(app)如果 __name__ == "__main__":fix_path()主要的()
Edit3:
要让此代码在所有其他导入之前运行,您可以将路径管理代码放在自己的应用程序基目录中的文件中(Python 可识别该目录中的所有内容,无需任何路径修改).
然后你只需确保这个导入
import fix_path
...在您的 main.py
文件中的所有其他导入之前列出.
这是一个完整的工作示例链接,以防我的解释不清楚.
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.
Simply place the short_url.py
file in your app's directory.
Sample App Engine project:
myapp/ app.yaml index.yaml main.py short_url.py views.py
And in views.py
(or wherever), you can then import like so:
import short_url
For more complex projects, perhaps a better method is to create a directory especially for dependencies; say lib
:
myapp/ lib/ __init__.py short_url.py app.yaml index.yaml main.py views.py
from lib import short_url
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()
Edit3:
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
...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 中导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!