How to get application root path in GAE

2019-04-09 06:38发布

I am using Jinja2 templates for my GAE Python application. Actually there are a couple of small applications inside one project. They are, for example, blog and site. So, the first one is for blog and the second one is for site =). I have this folders structure:

/
  /apps
    /blog
    /site
/templates
  /blog
  /site

I also have a code for accessing templates folder for each application. It looks like this:

template_dirs = []
template_dirs.append(os.path.join(os.path.dirname(__file__), 'templates/project'))

Of course, it doesn't work as it's wrong. It returns a string like this: base/data/home/apps/myapplication/1.348460209502075158/apps/project/templates/project

And I need it to return a string like this: base/data/home/apps/myapplication/1.348460209502075158/apps/templates/project How can I do that using absolute paths, not relative? I suppose I need to get the root of the my whole GAE project some way. Thanks!

3条回答
何必那么认真
2楼-- · 2019-04-09 07:11

Why not put an os.path.abspath around file

template_dirs.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates/project'))
查看更多
Anthone
3楼-- · 2019-04-09 07:13

It's kind of a kludge, and I didn't write this with the love and caring I write most of my code with, but maybe this will be useful for you...

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

Please note that for this to work on the SDK your application's root directory MUST be named the same as your application's ID.

Additionally, this makes assumptions about the directory structure used by Google on the production servers, so it's entirely possible that they could change something and break this.

查看更多
走好不送
4楼-- · 2019-04-09 07:33

The easiest way to get the root path of your app is to put a module in the root of your app, which stores the result of os.path.dirname(__file__), then import that where needed. Alternately, call os.path.dirname(module.__file__) on a module that's in the root of your app.

查看更多
登录 后发表回答