Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put Django startup code?

I'd like to have these lines of code executed on server startup (both development and production):

from django.core import management management.call_command('syncdb', interactive=False) 

Putting it in settings.py doesn't work, as it requires the settings to be loaded already.

Putting them in a view and accessing that view externally doesn't work either, as there are some middlewares that use the database and those will fail and not let me access the view.

Putting them in a middleware would work, but that would get called each time my app is accessed. An possible solution might be to create a middleware that does all the job and then removes itself from MIDDLEWARE_CLASSES so it's not called anymore. Can I do that without too much monkey-patching?

like image 746
Attila O. Avatar asked May 06 '10 13:05

Attila O.


People also ask

Which file runs first in Django?

For Django < 1.7. The number one answer does not seem to work anymore, urls.py is loaded upon first request. When using ./manage.py runserver ... this gets executed twice, but that is because runserver has some tricks to validate the models first etc ...


2 Answers

Write middleware that does this in __init__ and afterwards raise django.core.exceptions.MiddlewareNotUsed from the __init__, django will remove it for all requests :). __init__ is called at startup by the way, not at the first request, so it won't block your first user.

There is talk about adding a startup signal, but that won't be available soon (a major problem for example is when this signal should be sent)

Related Ticket: https://code.djangoproject.com/ticket/13024

Update: Django 1.7 includes support for this. (Documentation, as linked by the ticket)

like image 126
KillianDS Avatar answered Sep 28 '22 08:09

KillianDS


In Django 1.7+ if you want to run a startup code and,

1. Avoid running it in migrate, makemigrations, shell sessions, ...

2. Avoid running it twice or more

A solution would be:

file: myapp/apps.py

from django.apps import AppConfig  def startup():     # startup code goes here  class MyAppConfig(AppConfig):     name = 'myapp'     verbose_name = "My Application"     def ready(self):         import os         if os.environ.get('RUN_MAIN'):             startup() 

file: myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig' 

This post is using suggestions from @Pykler and @bdoering

like image 36
Joseph Bani Avatar answered Sep 28 '22 07:09

Joseph Bani