Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django shared library/classes

Tags:

python

django

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 would be the best location to place them?

e.x abstract models

regards,

like image 569
Mo J. Mughrabi Avatar asked Dec 18 '10 20:12

Mo J. Mughrabi


3 Answers

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.

like image 159
Fábio Diniz Avatar answered Oct 31 '22 18:10

Fábio Diniz


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.

like image 17
Josh Smeaton Avatar answered Oct 31 '22 17:10

Josh Smeaton


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?"

like image 14
whoami Avatar answered Oct 31 '22 19:10

whoami