Commit 28324252 authored by Elia Ponzio's avatar Elia Ponzio
Browse files

Feature api

parent 3e72511d
......@@ -65,3 +65,93 @@ docker-compose up -d
from django_celery_beat.models import PeriodicTask, IntervalSchedule
schedule, created = IntervalSchedule.objects.get_or_create(every=10,period=IntervalSchedule.SECONDS,)
PeriodicTask.objects.create(interval=schedule,name='hello_world',task='cynomys.tasks.example',)
## API Docs
### Token
You can create a token for your user in the admin menu
```
{"Authorization": "Token 68d2c6778abfd92c6a17b494e9b575bdba09c975"}
```
### Create a ping check
**URL:** /api/tasks/create_ping_check/
**Method:** POST
**Expects:**
```
{
"name": "name of your check",
"interval_id": "The id of the Interval (check created intervals for that ID)",
"name": "name of your check",
"host": "DNS or IP Address",
"timeout": "Ping response timeout in seconds",
}
```
### Create a http check
**URL:** /api/tasks/create_http_check/
**Method:** POST
**Expects:**
```
{
"name": "name of your check",
"interval_id": "The id of the Interval (check created intervals for that ID)",
"name": "name of your check",
"host": "URL, as an example: https://vshn.ch",
"httpcode": "Expected response code",
"timeout": "HTTP response timeout in seconds",
}
```
### Get Latest of a Task
**URL:** /api/tasks/<ID>/latest_delta
**Method:** GET
**Example Results:**
```
{
"Message": "Latest Delta, current status.",
"Deltas": {
"url": "/api/deltas/16/",
"task": "/api/tasks/4/",
"timestamp": "2021-06-25T07:30:09.017885Z",
"success": false,
"latest_check": "2021-06-25T07:30:09.017894Z",
"return_value": "Failed to Ping!"
}
}
```
### Get All Deltas of a Task
**URL:** /api/tasks/<ID>/get_all_deltas
**Method:** GET
**Example Results:**
```
{
"Message": "All deltas of this task.",
"Deltas": [
{
"url": "/api/deltas/16/",
"task": "/api/tasks/4/",
"timestamp": "2021-06-25T07:30:09.017885Z",
"success": false,
"latest_check": "2021-06-25T07:30:20.017894Z",
"return_value": "Failed to Ping!"
},
{
"url": "/api/deltas/15/",
"task": "/api/tasks/4/",
"timestamp": "2021-06-25T07:18:22.388531Z",
"success": true,
"latest_check": "2021-06-25T07:29:29.962111Z",
"return_value": "Success!"
},
...
]
}
```
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
from cynomys.models import Delta
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from rest_framework.reverse import reverse
from django_celery_beat.models import PeriodicTask, IntervalSchedule
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups', 'password')
class DeltaSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Delta
fields = ('url', 'task', 'timestamp', 'success', 'latest_check', 'return_value')
class PeriodicTaskSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PeriodicTask
fields = ('url', 'name', 'task', 'interval', 'args', 'kwargs', 'expire_seconds', 'enabled')
class IntervalScheduleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = IntervalSchedule
fields = ('url', 'every', 'period',)
from django.test import TestCase
# Create your tests here.
from django.urls import include, path
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'deltas', views.DeltaViewSet)
router.register(r'tasks', views.TaskViewSet)
router.register(r'intervals', views.IntervalViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions, authentication
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes, authentication_classes, action
from api.serializers import UserSerializer, DeltaSerializer, PeriodicTaskSerializer, IntervalScheduleSerializer
from cynomys.models import Delta
from django_celery_beat.models import PeriodicTask, IntervalSchedule
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class DeltaViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Delta.objects.all()
serializer_class = DeltaSerializer
permission_classes = [permissions.IsAuthenticated]
class TaskViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = PeriodicTask.objects.all()
serializer_class = PeriodicTaskSerializer
permission_classes = [permissions.IsAuthenticated]
@action(detail=True, methods=['GET'])
def get_all_deltas(self, request, pk=None):
deltas = Delta.objects.all().filter(task=pk).order_by('-latest_check')
serializer = DeltaSerializer(deltas, many=True, context={'request': request})
return Response({'Message': "All deltas of this task.", 'Deltas': serializer.data})
@action(detail=True, methods=['GET'])
def latest_delta(self, request, pk=None):
deltas = Delta.objects.filter(task=pk).latest('pk')
serializer = DeltaSerializer(deltas, many=False, context={'request': request})
return Response({'Message': "Latest Delta, current status.", 'Deltas': serializer.data})
@action(detail=False, methods=['POST'])
def create_ping_check(self, request):
task = PeriodicTask()
task.name = request.data['name']
task.task = "cynomys.tasks.check_ping"
task.interval = IntervalSchedule.objects.get(pk=request.data['interval_id'])
task.args = [request.data['host'], request.data['timeout']]
task.expire_seconds = 30
task.save()
task.kwargs = {"task_id": task.pk}
task.save()
serializer = PeriodicTaskSerializer(task, many=False, context={'request': request})
return Response({'Message': "Task Created.", 'Task': serializer.data})
@action(detail=False, methods=['POST'])
def create_http_check(self, request):
task = PeriodicTask()
task.name = request.data['name']
task.task = "cynomys.tasks.check_http"
task.interval = IntervalSchedule.objects.get(pk=request.data['interval_id'])
task.args = [request.data['host'], request.data['timeout'], request.data['httpcode']]
task.expire_seconds = 30
task.save()
task.kwargs = {"task_id": task.pk}
task.save()
serializer = PeriodicTaskSerializer(task, many=False, context={'request': request})
return Response({'Message': "Task Created.", 'Task': serializer.data})
class IntervalViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = IntervalSchedule.objects.all()
serializer_class = IntervalScheduleSerializer
permission_classes = [permissions.IsAuthenticated]
......@@ -40,6 +40,8 @@ DJANGO_APPS = (
)
THIRD_PARTY_APPS = (
'django_celery_beat',
'rest_framework',
'rest_framework.authtoken',
)
LOCAL_APPS = (
'cynomys',
......@@ -162,3 +164,12 @@ EMAIL_SUBJECT_PREFIX = "[cynomys] "
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# Rest
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
......@@ -19,4 +19,5 @@ from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cynomys.urls')),
path('api/', include('api.urls')),
]
......@@ -5,3 +5,5 @@ Django==3.2.4
django-cockroachdb>=3.2.1
psycopg2==2.9.1
requests==2.25.1
djangorestframework==3.12.4
Markdown==3.3.4
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