简体   繁体   中英

Make library folder visible to all python scripts in different dir/subdir with a GAE project directory

I have the following directory structure for my GAE project:

project:

  • library:
    • lib1.py
    • lib2/x.py
    • lib2/y.py
  • apps:
    • app1/app1.py
    • app2/app2.py
    • app2/async.py

how do I make the library folder visible to any app that will ever be created in the apps dir and its subdirs?

Alternatively it's possible to add the library directory to the sys.path

Create a __init__.py inside the library folder.

import os
import sys

def add_lib_path():
    lib_directory = os.path.dirname(os.path.abspath(__file__))
    if lib_directory not in sys.path:
       sys.path.insert(0, lib_directory)

In every file where you import libraries from the library folder add this code before the import statements:

from lib import add_lib_path
add_lib_path()

In this case all your imported libraries will behave as expected.

PYTHONPATH specifies a series of folders to start searches for imported modules.

GAE adds the folder that contains app.yaml to your PYTHONPATH.

So assuming that app.yaml is in the root of that structure (ie the folder that contains "library" and "apps") then any of your apps can import relative to there...

  from library import lib1

  from library/lib2 import x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM