如何在GAE中获取应用根路径
我在我的GAE Python应用程序中使用Jinja2模板。其实在一个项目里有几个小应用,比如说博客和网站。第一个是博客,第二个是网站=)。我的文件夹结构是这样的:
/
/apps
/blog
/site
/templates
/blog
/site
我还有一段代码用来访问每个应用的模板文件夹。代码是这样的:
template_dirs = []
template_dirs.append(os.path.join(os.path.dirname(__file__), 'templates/project'))
当然,这段代码并不好用,因为它是错的。它返回的字符串是这样的: base/data/home/apps/myapplication/1.348460209502075158/apps/project/templates/project
而我需要它返回这样的字符串: base/data/home/apps/myapplication/1.348460209502075158/apps/templates/project 我该怎么做才能使用绝对路径,而不是相对路径呢?我想我需要以某种方式获取整个GAE项目的根目录。 谢谢!
3 个回答
1
为什么不在file周围加上os.path.abspath呢?
template_dirs.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates/project'))
1
这有点像是个临时解决方案,我写这个的时候没有像写其他代码那样用心,但也许对你有帮助……
import os
def app_root():
"""Get the path to the application's root directory."""
app_id = os.environ['APPLICATION_ID']
path = os.environ['PATH_TRANSLATED']
path_parts = path.split(app_id, 1)
root_path = path_parts[0] + app_id
# If this is ran on Google's servers, there is an extra dir
# that needs to be traversed to get to the root
if not os.environ['SERVER_SOFTWARE'].startswith('Dev'):
root_path += '/' + path_parts[1].lstrip('/').split('/', 1)[0]
return root_path
请注意,要让这个在SDK上正常工作,你的应用根目录必须和你的应用ID同名。
另外,这个方法是基于谷歌在生产服务器上使用的目录结构来假设的,所以他们有可能会改动什么,导致这个方法失效。
15
获取你应用程序根目录的最简单方法是,在应用程序的根目录下放一个模块,这个模块里存储了 os.path.dirname(__file__)
的结果。然后在需要的地方导入这个模块。另一种方法是,直接在一个位于你应用程序根目录的模块上调用 os.path.dirname(module.__file__)
。