Commit 858dc4f9 authored by Yori Fournier's avatar Yori Fournier
Browse files

first commit

parents
pip install -r requirements.txt
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ArchGenConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'arch_gen'
from django.db import models
# Create your models here.
INTERFACES = [('tap', 'TAP'), ]
ACTIONS = [('save_to_file', 'save to file'), ]
class ArchiveDescriber(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
owner = models.ForeignKey('auth.User', related_name='archive_describers', on_delete=models.CASCADE)
interface_type = models.CharField(max_length=100, choices=INTERFACES)
action_type = models.CharField(max_length=100, choices=ACTIONS)
class Meta:
ordering = ['created']
# this wont' create a table
class TapArchiveDescriber_MixIn(models.Model):
interface_url = models.CharField(max_length=256, default='https://your-service.org/tap')
class Meta:
abstract = True
# this wont' create a table
class SaveToFileArchiveDescriber_MixIn(models.Model):
action_fileformat = models.CharField(max_length=10, default='.csv')
class Meta:
abstract = True
# the instance of this will be in both tables: ArchiveDescriber and in TapSaveToFileArchiveDescriber
class TapSaveToFileArchiveDescriber(ArchiveDescriber, TapArchiveDescriber_MixIn, SaveToFileArchiveDescriber_MixIn):
pass
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user
from rest_framework import serializers
from arch_gen.models import ArchiveDescriber, TapSaveToFileArchiveDescriber
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
archive_describers = serializers.PrimaryKeyRelatedField(many=True, queryset=ArchiveDescriber.objects.all())
lists = serializers.HyperlinkedIdentityField(view_name='user-archive-describers', format='api')
class Meta:
model = User
fields = ['id', 'username', 'archive_describers', 'lists']
class ArchiveDescriberSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
details = serializers.HyperlinkedIdentityField(view_name='archive-describer-detail', format='api')
class Meta:
model = ArchiveDescriber
fields = ['id', 'owner', 'title',
'interface_type',
'action_type',
'details',
]
class TapSaveToFileArchiveDescriberSerializer(serializers.ModelSerializer):
class Meta:
model = TapSaveToFileArchiveDescriber
fields = ['id', 'owner', 'title',
'interface_type', 'interface_url',
'action_type', 'action_fileformat']
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from arch_gen import views
urlpatterns = [
path('users/', views.UserList.as_view()),
path('users/<int:pk>/', views.UserDetail.as_view()),
path('users/<int:pk>/archive_describers/', views.user_archive_describer_list, name='user-archive-describers'),
path('archive_describers/', views.archive_describer_list),
path('archive_describers/<int:pk>/', views.archive_describer_detail, name='archive-describer-detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from arch_gen.models import ArchiveDescriber, TapSaveToFileArchiveDescriber
from arch_gen.serializers import ArchiveDescriberSerializer, TapSaveToFileArchiveDescriberSerializer
from arch_gen.permissions import IsOwnerOrReadOnly
# Create your views here.
from django.contrib.auth.models import User
from arch_gen.serializers import UserSerializer
from rest_framework import generics
from rest_framework import permissions
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
# UTILS
def get_archive_describer_child(parent, interface_type, action_type):
child_ref = str(interface_type.lower() + action_type.lower()).replace('_', '') + "archivedescriber"
child = getattr(parent, child_ref)
return(child)
def get_archive_describer_class(interface_type, action_type):
class_name = str(interface_type.lower() + ' ' + action_type.lower()).replace('_', ' ').title().replace(' ', '') + "ArchiveDescriber"
cls = globals().get(class_name)
return(cls)
def get_archive_describer_serializer_class(interface_type, action_type):
class_name = str(interface_type.lower() + ' ' + action_type.lower()).replace('_', ' ').title().replace(' ', '') + "ArchiveDescriberSerializer"
cls = globals().get(class_name)
return(cls)
@api_view(['GET', 'POST'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def archive_describer_list(request, format=None):
"""
List all code archive_describers, or create a new archive_describer.
"""
if request.method == 'GET':
archive_describers = ArchiveDescriber.objects.all()
serializer = ArchiveDescriberSerializer(archive_describers, many=True, context={'request': request})
return Response(serializer.data)
elif request.method == 'POST':
# print(request.data) # THIS IS HOW TO ACCESS THE DATA (prevent request.body at all costs)
serializer_class = get_archive_describer_serializer_class(request.data['interface_type'], request.data['action_type'])
# add the user to the data (Hacky... need a better way)
data = request.data.copy()
user = User.objects.filter(username=request.user.username)
data.update({"owner": user[0].id})
serializer = serializer_class(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'POST'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def user_archive_describer_list(request, pk, format=None):
"""
List user's code archive_describers, or create a new archive_describer.
"""
if request.method == 'GET':
user = User.objects.get(pk=pk)
archive_describers = ArchiveDescriber.objects.filter(owner=user)
serializer = ArchiveDescriberSerializer(archive_describers, many=True, context={'request': request})
return Response(serializer.data)
elif request.method == 'POST':
# print(request.data) # THIS IS HOW TO ACCESS THE DATA (prevent request.body at all costs)
serializer_class = get_archive_describer_serializer_class(request.data['interface_type'], request.data['action_type'])
# add the user to the data (Hacky... need a better way)
data = request.data.copy()
user = User.objects.filter(username=request.user.username)
data.update({"owner": user[0].id})
serializer = serializer_class(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly])
def archive_describer_detail(request, pk, format=None):
"""
Retrieve, update or delete a code archive_describer.
"""
try:
abstract_arch_descr = ArchiveDescriber.objects.get(pk=pk)
except ArchiveDescriber.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
arch_descr = get_archive_describer_child(abstract_arch_descr,
abstract_arch_descr.interface_type,
abstract_arch_descr.action_type)
if request.method == 'GET':
serializer_class = get_archive_describer_serializer_class(abstract_arch_descr.interface_type, abstract_arch_descr.action_type)
serializer = serializer_class(arch_descr)
return Response(serializer.data)
elif request.method == 'PUT':
serializer_class = get_archive_describer_serializer_class(abstract_arch_descr.interface_type, abstract_arch_descr.action_type)
serializer = serializer_class(arch_descr, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
arch_descr.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
"""
ASGI config for arch_rest_api project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arch_rest_api.settings')
application = get_asgi_application()
"""
Django settings for arch_rest_api project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-@xy%$g508v_z2)w=7mrlz63m&6lx*k+f$y--5ss6qkx&f@8k5^'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'arch_gen.apps.ArchGenConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'arch_rest_api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'arch_rest_api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
"""arch_rest_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', include('rest_framework.urls')),
path('', include('arch_gen.urls')),
]
"""
WSGI config for arch_rest_api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arch_rest_api.settings')
application = get_wsgi_application()
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arch_rest_api.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
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