Signal fix

This commit is contained in:
Mark Steadman 2014-06-16 23:37:28 +01:00
parent 1527148dcb
commit 7a0dac5ce4
7 changed files with 69 additions and 150 deletions

View file

@ -4,13 +4,11 @@ from django.db.models import Model
from bambu_buffer.exceptions import *
from bambu_buffer.models import BufferToken, BufferProfile, BufferedItem
from bambu_buffer.settings import POST_URL, TIMEOUT, AUTOPOST_MODELS
from bambu_buffer.sites import BufferSite
from datetime import datetime, date
from threading import Thread
import requests
__version__ = '2.0.1'
site = BufferSite()
class BufferThread(Thread):
def __init__(self, token, data, *args, **kwargs):
@ -105,5 +103,3 @@ def post(item, author, **kwargs):
)
BufferThread(token.token, data).start()
site.hookup_signals(AUTOPOST_MODELS)

View file

@ -1,40 +0,0 @@
from django.db import transaction
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from os import sys
class Command(BaseCommand):
help = 'Fake Buffer records for items in settings.BUFFER_AUTOPOST_MODELS'
@transaction.commit_on_success
def handle(self, *args, **options):
from django.contrib.contenttypes.models import ContentType
from bambu_buffer import site
from bambu_buffer.models import BufferedItem
for model, info in site._registry.items():
query = dict(
[
(key, callable(value) and value() or value)
for (key, value) in info['conditions'].items()
]
)
count = 0
for pk in model.objects.filter(**query).values_list('pk', flat = True):
item, created = BufferedItem.objects.get_or_create(
content_type = ContentType.objects.get_for_model(model),
object_id = pk
)
if not created:
count += 1
sys.stdout.write(
'Added fake Buffer item for %d %s\n' % (
count,
unicode(
count == 1 and model._meta.verbose_name or model._meta.verbose_name_plural
)
)
)

View file

@ -2,6 +2,7 @@ from django.db import models
from django.utils.timezone import pytz
from bambu_buffer.settings import PROFILES_URL, TIMEOUT
from bambu_buffer import log
from bambu_buffer.receivers import *
from datetime import datetime, timedelta
import requests, json
@ -113,4 +114,4 @@ class BufferedItem(models.Model):
class Meta:
unique_together = ('content_type', 'object_id')
db_table = 'buffer_buffereditem'
db_table = 'buffer_buffereditem'

67
bambu_buffer/receivers.py Normal file
View file

@ -0,0 +1,67 @@
from logging import getLogger
from django.db.models.loading import get_model
from django.db.models.signals import post_save
def post_save_receiver(sender, instance, **kwargs):
from bambu_buffer import post, settings
found = False
for m in [list(m) for m in settings.AUTOPOST_MODELS]:
if not any(m):
continue
name = m.pop(0)
app, model = name.lower().split('.')
if app != instance._meta.app_label and model != instance._meta.module_name:
continue
if any(m):
author_field = m.pop(0)
else:
author_field = 'author'
if any(m):
conditions = m.pop(0)
else:
conditions = {}
if any(m):
post_kwargs = m.pop(0)
else:
post_kwargs = {}
field = type(instance)._meta.get_field_by_name(author_field)
if not any(field) or field[0] is None:
continue
found = True
if not found:
return
if any(conditions):
query = dict(
[
(key, callable(value) and value() or value)
for (key, value) in conditions.items()
]
)
if not type(instance).objects.filter(
pk = instance.pk,
**query
).exists():
return
post(
instance,
getattr(instance, author_field),
**dict(
[
(key, callable(value) and value() or value)
for (key, value) in post_kwargs.items()
]
)
)
post_save.connect(post_save_receiver)

View file

@ -1,105 +0,0 @@
from logging import getLogger
from django.db.models.loading import get_model
from django.db.models.signals import post_save
def post_save_receiver(sender, instance, **kwargs):
from bambu_buffer import post, site
model = site.get_info(type(instance))
if not model or not any(model):
print '%s not registered' % (
unicode(type(instance)._meta.verbose_name).capitalize()
)
return
if any(model['conditions']):
query = dict(
[
(key, callable(value) and value() or value)
for (key, value) in model['conditions'].items()
]
)
if not type(instance).objects.filter(
pk = instance.pk,
**query
).exists():
print '%s does not match Buffer criteria' % unicode(
unicode(instance._meta.verbose_name).capitalize()
)
return
post(
instance,
getattr(instance,
model['author_field']
),
**dict(
[
(key, callable(value) and value() or value)
for (key, value) in model['post_kwargs'].items()
]
)
)
class BufferSite(object):
def __init__(self, *args, **kwargs):
self._registry = {}
def register(self, model, author_field, conditions = {}, post_kwargs = {}):
self._registry[model] = {
'author_field': author_field,
'conditions': conditions,
'post_kwargs': post_kwargs
}
def get_info(self, model):
return self._registry.get(model)
def hookup_signals(self, models):
logger = getLogger('bambu_buffer')
for m in [list(m) for m in models]:
if not any(m):
continue
name = m.pop(0)
if any(m):
author_field = m.pop(0)
else:
author_field = 'author'
if any(m):
conditions = m.pop(0)
else:
conditions = {}
if any(m):
post_kwargs = m.pop(0)
else:
post_kwargs = {}
try:
model = get_model(*name.split('.'), only_installed = False)
except:
logger.warn('Model %s not found' % name)
continue
if not model:
logger.warn('Model %s not found' % name)
continue
field = model._meta.get_field_by_name(author_field)
if not any(field) or field[0] is None:
raise Exception(
'Field %s not found in model %s' % (author_field, name)
)
self.register(model,
author_field = author_field,
conditions = conditions,
post_kwargs = post_kwargs
)
post_save.connect(post_save_receiver, sender = model)