def testCanGetForDate(self): now = datetime.datetime.now() # Test a model with an int pk. version = reversion.get_for_date(self.test11, now) self.assertEqual(version.field_dict["name"], "model1 instance1 version2") self.assertRaises(Version.DoesNotExist, lambda: reversion.get_for_date(self.test11, datetime.datetime(1970, 1, 1))) # Test a model with a str pk. version = reversion.get_for_date(self.test21, now) self.assertEqual(version.field_dict["name"], "model2 instance1 version2") self.assertRaises(Version.DoesNotExist, lambda: reversion.get_for_date(self.test21, datetime.datetime(1970, 1, 1)))
def history(self, request, uuid=None): mapped = { 'start': request.query_params.get('start'), 'end': request.query_params.get('end'), 'points_count': request.query_params.get('points_count'), 'point_list': request.query_params.getlist('point'), } serializer = HistorySerializer( data={k: v for k, v in mapped.items() if v}) serializer.is_valid(raise_exception=True) quota = self.get_object() serialized_versions = [] for point_date in serializer.get_filter_data(): serialized = {'point': datetime_to_timestamp(point_date)} try: version = reversion.get_for_date(quota, point_date) except Version.DoesNotExist: pass else: serializer = self.get_serializer() serializer.instance = version.object_version.object serialized['object'] = serializer.data serialized_versions.append(serialized) return response.Response(serialized_versions, status=status.HTTP_200_OK)
def setUp(self): self.customer = structure_factories.CustomerFactory() self.owner = structure_factories.UserFactory(username='******') self.customer.add_user(self.owner, structure_models.CustomerRole.OWNER) self.quota = factories.QuotaFactory(scope=self.customer) self.url = factories.QuotaFactory.get_url(self.quota, 'history') # Hook for test: lets say that revision was created one hour ago version = reversion.get_for_date(self.quota, timezone.now()) version.revision.date_created = timezone.now() - timedelta(hours=1) version.revision.save()
def items(self, obj): items = [] itemvalues = [] last_version = None for date in subscription_types[self.subtype](obj): v = None try: v = reversion.get_for_date(obj, date).field_dict except Version.DoesNotExist, e: pass if v and v!=last_version: last_version=v itemvalues.append(v)
def items(self, obj): items = [] itemvalues = [] last_version = None for date in subscription_types[self.subtype](obj): v = None try: v = reversion.get_for_date(obj, date).field_dict except Version.DoesNotExist, e: pass if v and v != last_version: last_version = v itemvalues.append(v)
def get_current_version(self, obj): """ Return current version ID for non-edit methods, otherwise 'Unknown'. When editing, a new version will be created by django-reversion. However, due to transaction timing the ID for this new Version hasn't yet been generated and stored by the time the response for the editing API call is generated. Rather than return the old, incorrect ID, we simply report 'Unknown' for editing API calls. An editing app will need to perform a new GET request to get the new version ID for the object. """ if self.context['request'].method in permissions.SAFE_METHODS: return reversion.get_for_date(obj, datetime.datetime.now()).id else: return 'Unknown'
def _check_current_version(self, instance): """ Check that the edited-version parameter matches the current version. If different, it indicates a probably "edit conflict": the submitted edit is being made to a stale version of the model. """ edited_version = self.context['request'].data['edited-version'] current_version = reversion.get_for_date( instance, datetime.datetime.now()).id if not current_version == edited_version: raise serializers.ValidationError(detail={ 'detail': 'Edit conflict error! The current version for this object ' 'does not match the reported version being edited.', 'current_version': current_version, 'submitted_data': self.context['request'].data, })
def destroy(self, request, *args, **kwargs): """ Check version is the latest. If so: record CommitDeletion, then delete. """ if 'edited-version' not in request.data: raise rest_framework.serializers.ValidationError(detail={ 'detail': 'Delete sumbissions to the API must include a parameter ' "'edited-version' that reports the version ID of the item " 'being deleted.' }) instance = self.get_object() current_version = reversion.get_for_date( instance, datetime.datetime.now()).id if not current_version == request.data['edited-version']: raise rest_framework.serializers.ValidationError(detail={ 'detail': 'Edit conflict error! The current version for this object ' 'does not match the reported version being deleted.', 'current_version': current_version, 'submitted_data': self.context['request'].data, }) self.record_destroy(request, instance) return super(RelationViewSet, self).destroy(request, *args, **kwargs)
def send_overvakingar(): for overvak in LokallagOvervaking.objects.filter( Q(deaktivert__isnull=True) | Q(deaktivert__gt=datetime.datetime.now()) ): epost_seq = overvak.epostar() if not epost_seq: # Noone to send to anyway continue if (datetime.datetime.now() - overvak.sist_oppdatert) < datetime.timedelta(days=6, seconds=22 * 60 * 60): # Har sendt epost for mindre enn 7 dagar sidan, so ikkje send noko no. # TODO: Dette er ein sjukt dårleg måte å gjera dette på, fiks betre continue sist_oppdatering = overvak.sist_oppdatert overvak.sist_oppdatert = datetime.datetime.now() medlem = overvak.lokallag.medlem_set.alle().filter(oppdatert__gt=sist_oppdatering) nye_medlem = list(medlem.filter(oppretta__gt=sist_oppdatering).exclude(status="I")) nye_infofolk = list(medlem.filter(oppretta__gt=sist_oppdatering, status="I")) # Alle andre, "gamle" medlemar medlem = medlem.exclude(oppretta__gt=sist_oppdatering) # Finn dei som har flytta til eit ANNA lokallag try: sist_statistikk = LokallagStat.objects.get( veke="{0:%Y-%W}".format(sist_oppdatering), lokallag=overvak.lokallag ) except LokallagStat.DoesNotExist: sist_statistikk = LokallagStat.objects.filter( oppretta__gt=sist_oppdatering, lokallag=overvak.lokallag ).order_by("-oppretta")[0] # stderr(u"LokallagStat for {0}, {1:%Y-%W} fanst ikkje. Brukar {2}" \ # .format(overvak.lokallag, # sist_oppdatering, # sist_statistikk)) if sist_statistikk: medlemar_sist = json.loads(sist_statistikk.interessante) medlemar_no = overvak.lokallag.medlem_set.interessante().values_list("pk", flat=True) vekkflytta_medlem = Medlem.objects.filter( pk__in=set(medlemar_sist) - set(medlemar_no), utmeldt_dato__isnull=True ) else: vekkflytta_medlem = [] tilflytta_medlem, utmeld_medlem, endra_medlem, ukjend_endring = [], [], [], [] for m in medlem: try: old = reversion.get_for_date(m, sist_oppdatering) except reversion.models.Version.DoesNotExist: continue new = reversion.get_for_object(m)[0] def _changed_field(k): if old.field_dict[k] == new.field_dict[k]: return False if old.field_dict[k] in (None, "", "None") and new.field_dict[k] in (None, "", "None"): return False if isinstance(old.field_dict[k], basestring) and "".join(old.field_dict[k].split()) == "".join( new.field_dict[k].split() ): return False return True changed_keys = filter(_changed_field, new.field_dict.keys()) def _humanify_pks(field, model): if field in changed_keys: old.field_dict[field] = ", ".join(namn_from_pks(model, map(int, old.field_dict[field]))) new.field_dict[field] = ", ".join(namn_from_pks(model, map(int, new.field_dict[field]))) _humanify_pks("val", Val) m.changed = [ (k, old.field_dict[k], new.field_dict[k]) for k in changed_keys if k not in ["_siste_medlemspengar", "innmeldingstype", "oppdatert", "oppretta", "nykel"] ] if "utmeldt_dato" in changed_keys and new.field_dict["utmeldt_dato"]: utmeld_medlem.append(m) elif "lokallag" in changed_keys: tilflytta_medlem.append(m) elif "status" in changed_keys and old.field_dict["status"] == "I": nye_medlem.append(m) elif m.changed: endra_medlem.append(m) else: ukjend_endring.append(m) if not ( len(nye_medlem) + len(nye_infofolk) + len(tilflytta_medlem) + len(endra_medlem) + len(utmeld_medlem) + len(vekkflytta_medlem) ): # Ikkje send noko dersom det er ingenting å melda continue ctx = { "nye_medlem": nye_medlem, "nye_infofolk": nye_infofolk, "endra_medlem": endra_medlem, "utmeld_medlem": utmeld_medlem, "ukjend_endring": ukjend_endring, "tilflytta_medlem": tilflytta_medlem, "vekkflytta_medlem": vekkflytta_medlem, } msg = create_overvaking_email(epost_seq, overvak, overvak.lokallag, sist_oppdatering, **ctx) try: msg.send() except smtplib.SMTPRecipientsRefused: # TODO Do logging continue overvak.save() return "Ferdig"