django shared library/classes

后端 未结 4 1435
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-08 08:21

Am new to django and was looking for advice where to place my shared library. Am planning on creating classes that I want to use across all my apps within the project. Where wou

4条回答
  •  半阙折子戏
    2021-02-08 08:42

    We usually set our projects up like this:

    /site/
        __init__.py
        manage.py
        settings.py
        urls.py
        /apps/
            __init__.py
            /appA/
                __init__.py
            /appB/
                __init__.py
        /lib/
            __init__.py
            /django-lib/
                __init__.py
            /shared-lib/
                __init__.py
    

    Just make sure your site directory is on your python path:

    import sys
    sys.path.append('/path/to/site/')
    

    Also, ensure that an init.py exists in site, apps, and lib so they can be treated as modules using dot notation imports (import site.lib.shared-lib)

    Edit:

    In answer to your question regarding your python path, it all has to do with where your 'manage.py' or equivalent file resides. If it is under the /site/ directory (next to apps and lib) then the PYTHONPATH should be fine.

    You need to make sure that every directory contains an empty file called __init__.py. This tells Python to treat that directory as a module. See the new and improved ASCII art above.

提交回复
热议问题