What is a good way to find relative paths in Google App Engine?

So, I did the trivial “workouts” using GAE. Now I would like to build something with a more complex directory structure. Sort of:

siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... 

.. etc. Controllers will handle Python module requests. Then they would need to find (Django-style) templates in related folders. Most of the demo applications I've seen allow template paths as follows:

 path = os.path.join(os.path.dirname(__file__), 'myPage.html') 

... the __ file __ property allows the currently executing script. So, in the above example, if a Python script was run in controllers / controller 1 /, then "myPage.html" allowed the same directory - controllers / controller 1 / myPage.html - and I would prefer to cleanly separate my code and templates into Python

The solution I hack feels ... hacky:

 base_paths = os.path.split(os.path.dirname(__file__)) template_dir = os.path.join(base_paths[0], "templates") 

So, I just discard the last element of the path for the current script run and add the template directory to the new path. The other (non-GAE) solutions I've seen to solve Python paths seem pretty heavyweight (like splitting paths into lists and managing them). Django seems to have an answer to this question, but I would rather stick with the GAE API, as well as create a complete Django application and modify it for GAE.

I assume that something hard-coded will not be a starter, since applications live on an endless farm of Google servers. So what's the best way?

+4
source share
2 answers

You cannot use relative paths, as Tony suggests, because you have no guarantee that the path from your working directory to the application directory will remain the same.

The correct solution is to either use os.path.split as you do, or use something like:

 path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html') 

My usual approach is to generate the path to the template directory using the above method and save it as a member of my controller object and provide a getTemplatePath method that takes the provided file name and appends it to the base name.

+4
source

The dirname function returns an absolute path, uses relative paths. See what the current directory is when your controllers are running with os.path.abspath(os.path.curdir) , and create a path to the templates relative to this location (of course, without os.path.abspath ).

This will only work if the current directory is somewhere inside siteroot, otherwise you can do something like this:

 template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "templates") 
+1
source

Source: https://habr.com/ru/post/1276682/


All Articles