django shared library/classes

后端 未结 4 1358
佛祖请我去吃肉
佛祖请我去吃肉 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:40

    What I learned from Two Scoops of Django is that you put the shared code inside a Django app that you create on your own called core.

    To use the core app then is similar to how you cross-use classes from other apps.

    To learn more, go to Chapter 28 of the book titled: "What About Those Random Utilities?"

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-08 08:55

    If the shared library is going to be used in others projects as well you can make a installer using distutils. But if it's only for the apps in the project you can take AntonioP's answer.

    Remember that the root of your project (folder that contains manage.py) is always in your PYTHON_PATH when you run your django project, so you can create a folder deps or dependencies or extra or anything you like it that contains your shared libraries.

    0 讨论(0)
  • 2021-02-08 09:01

    Wherever you want, you can import them if they are in the PYTHON_PATH.

    0 讨论(0)
提交回复
热议问题