Wednesday, March 9, 2016

Re: execute code at startup

I think if I were doing this, I would write a custom management command to update the tables, and run it at system startup time. Management commands are easy to debug and well documented.

On Tuesday, March 8, 2016 at 10:38:25 AM UTC-7, Julien Greard wrote:
Hello,

I am using Django 1.9.3. I have a project with several apps. I would like to update the tables of one of the app at the startup of the project.

I have all the code written, it looks like the following (it's an example):

from my_app.models import My_table

def on_startup():
     my_thread = Thread(execute = populate_tables, loopmode = True, background = True) # thread running in loopmode in background
     my_thread.start() # starts the thread and returns

def populate_tables()
     response = call_webservice() # let's imagine this method returns data for creating a new model instance
     My_table(response).save() # this save() isn't threadsafe in this example, but that's not my point ;-)

So far, with Django 1.6.5, I came with some code from the __init__.py file of my app. It was working, but I thought it was quite ugly (starting a thread with an "import" looks really like hidden code).

I saw in Django 1.9 the "ready()" method. But it's written in the documentation to not deal with models in this method so I am confused.

I could add the startup code in the command starting my server but this startup code is app oriented and in my opinion, the projects has nothing to do with my app.

What do you recommend?


I'd be happy to provide more info if needed.

Thanks in advance,

Julien Gréard

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/49d4a061-973e-4e54-b99a-383fdbcb2822%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment