Skip to content

Commit

Permalink
django: migrate to new ReST API endpoint
Browse files Browse the repository at this point in the history
- Adapt serializer to new format

Signed-off-by: Jonas Remmert <jremmert@gmx.net>
  • Loading branch information
jonas-rem committed Jun 5, 2024
1 parent d9043d1 commit 354d218
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 30 deletions.
39 changes: 18 additions & 21 deletions server/django/sensordata/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,46 +50,43 @@ class ValueSerializer(serializers.Serializer):

class LwM2MSerializer(serializers.Serializer):
ep = serializers.CharField(max_length=255)
res = serializers.CharField(max_length=255)
obj_id = serializers.IntegerField(required=False)
val = ValueSerializer()


def create(self, validated_data):
ep = validated_data['ep']
res = validated_data['res']
val = validated_data['val']

# ep maps to Device.endpoint
device, _ = Device.objects.get_or_create(endpoint=ep)

# Check if value is an object with instances
if val['kind'] == 'obj' and 'instances' in val:
# Check if value is an object with instances (Composite resource)
if val['kind'] == 'obj':
obj_id = val.get('id')
for instance in val['instances']:
for resource in instance['resources']:
self.handle_resource(device, res, resource)
pass
self.handle_resource(device, obj_id, resource)
else:
# Single resource handling
self.handle_resource(device, res, val)
try:
obj_id = validated_data.get('obj_id')
except KeyError as e:
logger.error(f"Missing required fields: {e}")
raise serializers.ValidationError(f"Missing required fields: {e}")
self.handle_resource(device, obj_id, val)

return device

def handle_resource(self, device, res, resource):
# Parse resource path to get object_id and resource_id
resource_path_parts = res.strip('/').split('/')
if len(resource_path_parts) == 3:
object_id = int(resource_path_parts[0])
resource_id = int(resource_path_parts[2])
elif resource_path_parts[0].isdigit():
object_id = int(resource_path_parts[0])
resource_id = resource['id']
else:
logger.error(f"Invalid resource path: {res}")
raise serializers.ValidationError("Invalid resource path")

def handle_resource(self, device, obj_id, resource):
res_id = resource['id']
# Fetch resource information from Database
resource_type = ResourceType.objects.get(object_id=object_id,
resource_id=resource_id)
resource_type = ResourceType.objects.get(object_id=obj_id,
resource_id=res_id)
if not resource_type:
raise serializers.ValidationError(f"Resource type {object_id}/{resource_id} not found")
raise serializers.ValidationError(f"Resource type {obj_id}/{res_id} not found")

logger.debug(f"Adding resource_type: {resource_type}")
data_type = resource_type.data_type
Expand Down
4 changes: 2 additions & 2 deletions server/django/sensordata/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.urls import path
from .views import CreateSensorDataView
from .views import PostResourceView

urlpatterns = [
path('endpointdata/', CreateSensorDataView.as_view(), name='add_sensor_data'),
path('resource', PostResourceView.as_view(), name='post_resource'),
]
10 changes: 4 additions & 6 deletions server/django/sensordata/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@
logger = logging.getLogger(__name__)


class CreateSensorDataView(APIView):
def post(self, request):
class PostResourceView(APIView):

def post(self, request):
serializer = LwM2MSerializer(data=request.data, many=False)
if serializer.is_valid():
serializer.save()
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
else:
print(serializer.errors)
logger.error(f"Errors: {serializer.errors}")
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
logger.error(serializer.errors)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2 changes: 1 addition & 1 deletion server/django/server/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('sensordata.urls')),
path('leshan_api/', include('sensordata.urls')),
]

0 comments on commit 354d218

Please sign in to comment.