问题
I have created a few post_save
signals but I was wondering if there will be performance issues later on. For example, I have something like this:
def my_signal(sender, **kwargs):
# some minimal processing
posts = len(MyPosts.objects.filter(date__gte=variable))
if entries == "20":
# crate an object and assign it to the post's author.
post_save.connect(my_signal, sender=MyPosts)
Let's say I have a very busy site and this is firing each time a post is created. Is it too bad to performance?. Is there a way to fire signals in a more slow-paced way (maybe, once a day or every few requests)?.
UPDATE:
Another question: is Django smart enough to compound the .save()
call with the post_save
signal into one database request or is it doing a couple of requests here?.
Thanks!
回答1:
The performance impact of your signal handlers depends of course on their functionality. But you should be aware of the fact that they are executed synchronously when the signal is fired, so if there's a lot of action going on in the handlers (for example a lot of database calls) the execution will be delayed.
Django itself doesn't offer you another opportunity to integrate signal handlers, but if necessary you should have a look in to django-celery which should enable you to call tasks asynchronously from within a signal handler for example...
回答2:
Given that signals are executed synchronously the performance of signals will depend greatly on how many handlers you are connecting and what code those execute when called. The original insert/update query will have already been executed when the post_save
signal fires. If you want to make some changes to the model data prior to the query execution then you can do that in a pre_save
handler instead. Some cases can also be handled by database triggers.
No, Django isn't "smart-enough" to combine queries that might be executed in an arbitrary number of attached Python functions into a single query. Nor is it able to combine update/inserts into a single query when they might insert into multiple tables as your use case describes. Django can however handle these within a single transaction.
django-celery, django-ztask, taskmaster and etc are designed for more complex tasks that need to be handled outside the request/response cycle. For tasks that only need to run once or twice a day you can also just write a custom management command and use cron.
来源:https://stackoverflow.com/questions/10839834/performance-of-signals-in-django