Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add initial implementation for history tracking #13

Merged
merged 3 commits into from
Sep 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions akb/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,56 @@
# Generated by Django 2.2.12 on 2020-07-07 14:12
# Generated by Django 2.2.12 on 2020-08-09 18:10

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Object',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('oid', models.BigIntegerField(unique=True)),
('oid', models.BigIntegerField(primary_key=True, serialize=False)),
('description', models.TextField(blank=True)),
('simbadid', models.CharField(blank=True, max_length=256)),
('changed_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.SlugField(max_length=256, unique=True)),
('priority', models.IntegerField()),
('description', models.TextField(blank=True)),
],
options={
'ordering': ['priority'],
},
),
migrations.AddIndex(
model_name='tag',
index=models.Index(fields=['name'], name='akb_tag_name_32e7bd_idx'),
),
migrations.AddIndex(
model_name='tag',
index=models.Index(fields=['priority'], name='akb_tag_priorit_361b7a_idx'),
),
migrations.AddField(
model_name='object',
name='tags',
field=models.ManyToManyField(related_name='tagged_objects', to='akb.Tag'),
name='changed_by',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),
),
migrations.AddIndex(
migrations.AddField(
model_name='object',
index=models.Index(fields=['oid'], name='akb_object_oid_c77fb7_idx'),
name='tags',
field=models.ManyToManyField(related_name='tagged_objects', to='akb.Tag'),
),
]
18 changes: 0 additions & 18 deletions akb/migrations/0002_object_simbadid.py

This file was deleted.

26 changes: 0 additions & 26 deletions akb/migrations/0003_tag_priority.py

This file was deleted.

18 changes: 0 additions & 18 deletions akb/migrations/0004_tag_priority_unique.py

This file was deleted.

18 changes: 0 additions & 18 deletions akb/migrations/0005_tag_description.py

This file was deleted.

21 changes: 15 additions & 6 deletions akb/models.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
from django.db import models
from django.contrib.auth.models import User
import reversion

class TagManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name = name)

class Tag(models.Model):
name = models.SlugField(max_length=256, blank = False, unique = True)
priority = models.IntegerField(unique = False, blank = False)
description = models.TextField(blank = True)

objects = TagManager()

def natural_key(self):
return (self.name,)

class Meta:
indexes = [
models.Index(fields=['name']),
models.Index(fields=['priority']),
]
ordering = ['priority']

@reversion.register(use_natural_foreign_keys = True)
class Object(models.Model):
oid = models.BigIntegerField(unique = True, blank = False)
oid = models.BigIntegerField(primary_key = True, blank = False)
description = models.TextField(blank = True)
tags = models.ManyToManyField("Tag", related_name="tagged_objects")
simbadid = models.CharField(max_length = 256, blank = True)

class Meta:
indexes = [
models.Index(fields=['oid']),
]
changed_at = models.DateTimeField(auto_now = True)
changed_by = models.ForeignKey(User, on_delete=models.PROTECT, blank = False)
7 changes: 6 additions & 1 deletion akb/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@ class Meta:

class ObjectSerializer(serializers.ModelSerializer):
tags = serializers.SlugRelatedField(many=True, slug_field='name', queryset=models.Tag.objects, default=[])
changed_by = serializers.SlugRelatedField(many=False, slug_field='username', allow_null=False, read_only=True)

def save(self):
self.validated_data['changed_by'] = self.context['request'].user
super(ObjectSerializer, self).save()

class Meta:
model = models.Object
fields = ('id', 'oid', 'description', 'simbadid', 'tags')
fields = ('oid', 'description', 'simbadid', 'tags', 'changed_by', 'changed_at')

class UserSerializer(serializers.ModelSerializer):
class Meta:
Expand Down
2 changes: 2 additions & 0 deletions akb/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'reversion',
'akb',
]

Expand All @@ -51,6 +52,7 @@
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'reversion.middleware.RevisionMiddleware',
]

# from rest_framework.authtoken.models import Token
Expand Down
23 changes: 20 additions & 3 deletions akb/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from akb import models, serializers
from rest_framework import viewsets
from django.utils.encoding import force_str
from json import JSONDecoder
from rest_framework import viewsets, status
from rest_framework.settings import api_settings
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, action, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from reversion.models import Version

class TagViewSet(viewsets.ModelViewSet):
queryset = models.Tag.objects.all()
Expand All @@ -13,8 +16,22 @@ class TagViewSet(viewsets.ModelViewSet):
class ObjectViewSet(viewsets.ModelViewSet):
queryset = models.Object.objects.prefetch_related('tags').all()
serializer_class = serializers.ObjectSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
lookup_field = 'oid'

@action(detail=True, methods=['GET'])
def log(self, request, oid=None):
decoder = JSONDecoder()

def decode(x):
obj = decoder.decode(force_str(x.serialized_data.encode("utf8")))[0]
return obj['fields']

o = self.get_object()
entries = [decode(x) for x in Version.objects.get_for_object(o)]

return Response(entries, status=status.HTTP_200_OK)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def whoami(request):
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
Django
djangorestframework
django-reversion > 3.0.7
dj-database-url
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import sys
from setuptools import setup

# allow setup.py to be run from any path
Expand Down Expand Up @@ -29,6 +28,7 @@
'Django',
'djangorestframework',
'dj-database-url',
'django-reversion > 3.0.7',
]
)

59 changes: 56 additions & 3 deletions tests/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
from akb.models import Object, Tag
import reversion

class ObjectTest(TestCase):
def setUp(self):
Expand All @@ -19,10 +20,11 @@ def test_object_create1(self):
'oid': 695211400132640,
'description': 'text'}, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
pk = response.json()['id']
pk = response.json()['oid']
o = Object.objects.get(pk=pk)
self.assertEqual(o.oid, 695211400132640)
self.assertEqual(o.description, 'text')
self.assertEqual(o.changed_by, self.user)

def test_object_create2(self):
tags = [Tag.objects.create(name="thetag", priority=1), Tag.objects.create(name="othertag", priority=2)]
Expand All @@ -32,20 +34,71 @@ def test_object_create2(self):
'description': 'text',
'tags': ["thetag", "othertag"]}, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
pk = response.json()['id']
pk = response.json()['oid']
o = Object.objects.get(pk=pk)
self.assertEqual(o.oid, 695211400132640)
self.assertEqual(o.description, 'text')
self.assertListEqual(list(o.tags.all()), tags)
self.assertListEqual(list(tags[0].tagged_objects.all()), [o,])
self.assertListEqual(list(tags[1].tagged_objects.all()), [o,])
self.assertEqual(o.changed_by, self.user)

def test_object_create3(self):
wrong_user = User.objects.get_or_create(username='alice')
url = reverse('object-list')
response = self.client.post(url, {
'oid': 695211400132640,
'changed_by': 'alice',
'description': 'text'}, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
pk = response.json()['oid']
o = Object.objects.get(pk=pk)
self.assertEqual(o.oid, 695211400132640)
self.assertEqual(o.description, 'text')
self.assertEqual(o.changed_by, self.user)

def test_object_create4(self):
url = reverse('object-list')
response = self.client.post(url, {
'oid': 695211400132640,
'description': 'text'}, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
o = Object.objects.get(pk=695211400132640)
self.assertEqual(o.description, 'text')
self.assertEqual(o.changed_by, self.user)

newuser, _ = User.objects.get_or_create(username='bob')
token = Token.objects.create(user=newuser)
newclient = APIClient()
newclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

url = reverse('object-detail', args=[695211400132640])
response = newclient.put(url, {
'oid': 695211400132640,
'description': 'new text'}, format='json')
o = Object.objects.get(pk=695211400132640)
self.assertEqual(o.description, 'new text')
self.assertEqual(o.changed_by, newuser)

def test_object_lookup1(self):
tags = [Tag.objects.create(name="thetag", priority=1), Tag.objects.create(name="othertag", priority=2)]
o = Object.objects.create(oid = 695211400132640, description = 'description')
o = Object.objects.create(oid = 695211400132640, description = 'description', changed_by=self.user)
o.tags.set(tags)
o.save()
url = reverse('object-detail', args=[695211400132640])
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["oid"], 695211400132640)

def test_object_log1(self):
tags = [Tag.objects.create(name="thetag", priority=1), Tag.objects.create(name="othertag", priority=2)]
with reversion.create_revision():
o = Object.objects.create(oid = 695211400132640, description = 'description', changed_by=self.user)
o.tags.set([tags[0]])
o.save()
with reversion.create_revision():
o.tags.set(tags)
o.save()
url = reverse('object-log', args=[695211400132640])
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)