tags:

views:

103

answers:

4

I've been doing some class hacking in Django. And I call my changes from settings.py as I figure this runs before anything else.

However, I've just come across a situation where this doesn't work for me. So, is there another place after settings.py, which I can guarantee will always be run by the server before it starts handling any requests?

A: 

I'm not sure exactly what you mean by 'class hacking' but have you tried calling your changes from ./manage.py?

From the docs:

In addition, manage.py is automatically created in each Django project. manage.py is a thin wrapper around django-admin.py that takes care of two things for you before delegating to django-admin.py:

It puts your project’s package on sys.path. It sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project’s settings.py file.

so if you have some stuff that you want to run after settings.py this might be the case if its a hack you're after.

HTH

chiggsy
-1 Under any production setup, manage.py is never imported or run at all.
Carl Meyer
A: 

Something like the request_started signal?

oggy
this looks promising
interstar
-1 If you're monkeypatching built-in classes (what I presume you mean by 'class hacking'), it's crazy to do something on every single request when it only needs to be done once.
Carl Meyer
A: 

If you want to put code somewhere in your django project that will get run for certain every time you start up django, pick an app form INSTALLED_APPS. Both the __init__.py and the models.py will be run for sure. They are good places for things like signals or anything you must register.

defrex
-1 Django does not guarantee that all models will be loaded before any requests are served. Models are only actually loaded if they are imported, or if somebody requests the full list of apps from the app cache.
Carl Meyer
+1  A: 

You should never put code in settings.py that requires importing anything from any part of Django. Since many parts of Django require settings to be available, this is very likely to get you into circular import problems.

Your ROOT_URLCONF (urls.py) is a reasonable place to put project-level code that you want run once for each server Python process, before any requests are served.

If the code is specific to a particular app (and only needed if that app is in use) then you could put it in that app's models.py or init.py.

For a broader look at the issue, see this blog post.

Carl Meyer