How to get the root path of an application in GAE

I am using Jinja2 templates for my GAE Python application. In fact, in one project there are several small applications. This is, for example, a blog and a website. So, the first for the blog, and the second for the site =). I have this folder structure:

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

I also have code to access the 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, this does not work, as it is wrong. It returns a string as follows: database / data / home / application / MyApplication / + 1.3448460209502075158 / application / project / templates / project

, :   ////MyApplication/1,348460209502075158/// , , ? , - GAE. !

+5
3

- , os.path.dirname(__file__), , . os.path.dirname(module.__file__) , .

+14

os.path.abs

template_dirs.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates/project'))
+1

This is a kind of kludge, and I did not write it with love and care, I write most of my code, but perhaps it will be useful for you ...

import os
def app_root():
    """Get the path to the application 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 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 to work with the SDK, the root directory of your application MUST be named the same as your application identifier.

In addition, it makes assumptions about the directory structure used by Google on production servers, so it is quite possible that they can change something and break it.

+1
source

All Articles