Anonymous Coward
Anonymous Coward

Reputation: 886

Dependency injection in Django

I have a factory-object which I'd like to make available to certain views in Django. The factory does not change the any state, it only creates instances. Instead of instantiating the factory in each view I'd like to create one instance and register it on server-startup.

Is this possible in Django and if so how? Otherwise what is the Pythonic/Djangonic way to do it?

Upvotes: 2

Views: 2116

Answers (1)

Anentropic
Anentropic

Reputation: 33853

It's enough to put the code in one of the files imported by Django on startup, such as:

  • settings.py
  • myapp/__init__.py where myapp is an app in INSTALLED_APPS setting var
  • myapp/models.py where myapp is an app in INSTALLED_APPS setting var

Your code doesn't have to go in the actual file above, you could put it in a separate file as long as you import that from one of the files above.

Upvotes: 2

Related Questions