Commit fde2f2c8 authored by Jean-Baptiste's avatar Jean-Baptiste

update: federated GET

parent bf684d21
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-09-05 15:42
# Generated by Django 1.11 on 2019-09-06 06:42
from __future__ import unicode_literals
from django.db import migrations, models
from django.db import migrations
import djangoldp.fields
class Migration(migrations.Migration):
......@@ -16,9 +17,9 @@ class Migration(migrations.Migration):
model_name='ldpsource',
name='container',
),
migrations.AlterField(
migrations.AddField(
model_name='ldpsource',
name='id',
field=models.URLField(primary_key=True, serialize=False),
name='urlid',
field=djangoldp.fields.LDPUrlField(null=True, unique=True),
),
]
......@@ -5,6 +5,7 @@ from django.urls import get_resolver
from django.utils.datastructures import MultiValueDict, MultiValueDictKeyError
from django.utils.decorators import classonlymethod
from djangoldp.fields import LDPUrlField
from djangoldp.permissions import LDPPermissions
User._meta.rdf_type = "foaf:user"
......@@ -12,6 +13,7 @@ User._meta.owner_field = "id"
class Model(models.Model):
urlid = LDPUrlField(null=True, unique=True)
@classmethod
def get_view_set(cls):
......@@ -133,20 +135,26 @@ class Model(models.Model):
permissions = permission_class().filter_user_perms(user_or_group, obj_or_model, permissions)
return [{'mode': {'@type': name.split('_')[0]}} for name in permissions]
@classmethod
def is_external(cls, value):
try:
return value.urlid is not None
except:
return False
class LDPSource(Model):
id = models.URLField(primary_key=True)
federation = models.CharField(max_length=255)
class Meta:
rdf_type = 'ldp:Container'
ordering = ('federation',)
container_path = 'sources'
lookup_field = 'id'
lookup_field = 'federation'
permissions = (
('view_source', 'acl:Read'),
('control_source', 'acl:Control'),
)
def __str__(self):
return "{}: {}".format(self.federation, self.id)
return "{}: {}".format(self.federation, self.urlid)
......@@ -184,7 +184,10 @@ class JsonLdField(HyperlinkedRelatedField):
class JsonLdRelatedField(JsonLdField):
def to_representation(self, value):
try:
return {'@id': super().to_representation(value)}
if Model.is_external(value):
return {'@id': value.urlid }
else:
return {'@id': super().to_representation(value)}
except ImproperlyConfigured:
return value.pk
......@@ -223,10 +226,20 @@ class JsonLdIdentityField(JsonLdField):
def to_representation(self, value: Any) -> Any:
try:
return Hyperlink(value.webid(), value)
if isinstance(value, str):
return Hyperlink(value, value)
else:
return Hyperlink(value.webid(), value)
except AttributeError:
return super().to_representation(value)
def get_attribute(self, instance):
if Model.is_external(instance):
return instance.urlid
else:
return super().get_attribute(instance)
class LDPSerializer(HyperlinkedModelSerializer):
url_field_name = "@id"
......@@ -254,10 +267,10 @@ class LDPSerializer(HyperlinkedModelSerializer):
for field in data:
if isinstance(data[field], dict) and '@id' in data[field]:
data[field]['@id'] = data[field]['@id'].format(Model.container_id(obj), str(getattr(obj, slug_field)))
if not ('@id' in data or 'id' in data):
if 'urlid' in data and data['urlid'] is not None:
data['@id'] = data.pop('urlid')['@id']
if not '@id' in data:
data['@id'] = '{}{}'.format(settings.SITE_URL, Model.resource(obj))
if 'id' in data:
data['@id'] = data.pop('id')
rdf_type = Model.get_meta(obj, 'rdf_type', None)
rdf_context = Model.get_meta(obj, 'rdf_context', None)
if rdf_type is not None:
......
......@@ -42,14 +42,17 @@ class TestGET(APITestCase):
def test_get_filtered_fields(self):
skill = Skill.objects.create(title="Java", obligatoire="ok", slug="1")
skill2 = Skill.objects.create(title="Java", obligatoire="ok", slug="2")
skill3 = Skill.objects.create(urlid="http://external/skills/1")
job = JobOffer.objects.create(title="job", slug="1")
job.skills.add(skill)
job.skills.add(skill2)
job.skills.add(skill3)
job.save()
response = self.client.get('/job-offers/{}/'.format(job.slug), content_type='application/ld+json')
self.assertEqual(response.status_code, 200)
self.assertIn('recent_skills', response.data)
self.assertEqual(response.data['recent_skills']['@id'], "http://happy-dev.fr/job-offers/1/recent_skills/")
self.assertEqual(response.data['skills']['ldp:contains'][2]['@id'], "http://external/skills/1")
def test_get_reverse_filtered_fields(self):
skill = Skill.objects.create(title="Java", obligatoire="ok", slug="1")
......
......@@ -13,6 +13,6 @@ class TestSource(APITestCase):
pass
def test_get_resource(self):
source = LDPSource.objects.create(federation="source_name", id="http://bar.foo/")
source = LDPSource.objects.create(federation="source_name", urlid="http://bar.foo/")
response = self.client.get('/sources/{}/'.format(source.federation), content_type='application/ld+json')
self.assertEqual(response.status_code, 200)
import json
from django.contrib.auth.models import User
from django.test import TestCase
from rest_framework.test import APIRequestFactory, APIClient
from djangoldp.tests.models import Resource, JobOffer, Invoice, Batch
class TestTemp(TestCase):
......@@ -16,4 +12,3 @@ class TestTemp(TestCase):
def tearDown(self):
pass
......@@ -17,7 +17,7 @@ def __clean_path(path):
urlpatterns = [
url(r'^sources/(?P<federation>\w+)/', LDPSourceViewSet.urls(model=LDPSource, fields=['federation', 'id'],
url(r'^sources/(?P<federation>\w+)/', LDPSourceViewSet.urls(model=LDPSource, fields=['federation', 'urlid'],
permission_classes=[LDPPermissions], )),
url(r'^\.well-known/webfinger/?$', WebFingerView.as_view()),
]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment