Django
This commit is contained in:
5
apps/dyn_api/__init__.py
Normal file
5
apps/dyn_api/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
8
apps/dyn_api/admin.py
Normal file
8
apps/dyn_api/admin.py
Normal file
@@ -0,0 +1,8 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
10
apps/dyn_api/apps.py
Normal file
10
apps/dyn_api/apps.py
Normal file
@@ -0,0 +1,10 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
class DynApiConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'apps.dyn_api'
|
||||
63
apps/dyn_api/helpers.py
Normal file
63
apps/dyn_api/helpers.py
Normal file
@@ -0,0 +1,63 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
import datetime, sys, inspect, importlib
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from django.db import models
|
||||
from django.http import HttpResponseRedirect, HttpResponse
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
class Utils:
|
||||
@staticmethod
|
||||
def get_class(config, name: str) -> models.Model:
|
||||
return Utils.model_name_to_class(config[name])
|
||||
|
||||
@staticmethod
|
||||
def get_manager(config, name: str) -> models.Manager:
|
||||
return Utils.get_class(config, name).objects
|
||||
|
||||
@staticmethod
|
||||
def get_serializer(config, name: str):
|
||||
class Serializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Utils.get_class(config, name)
|
||||
fields = '__all__'
|
||||
|
||||
return Serializer
|
||||
|
||||
@staticmethod
|
||||
def model_name_to_class(name: str):
|
||||
|
||||
model_name = name.split('.')[-1]
|
||||
model_import = name.replace('.'+model_name, '')
|
||||
|
||||
module = importlib.import_module(model_import)
|
||||
cls = getattr(module, model_name)
|
||||
|
||||
return cls
|
||||
|
||||
def check_permission(function):
|
||||
@wraps(function)
|
||||
def wrap(viewRequest, *args, **kwargs):
|
||||
|
||||
try:
|
||||
|
||||
# Check user
|
||||
if viewRequest.request.user.is_authenticated:
|
||||
|
||||
return function(viewRequest, *args, **kwargs)
|
||||
|
||||
# For authentication for guests
|
||||
return HttpResponseRedirect('/login/')
|
||||
|
||||
except Exception as e:
|
||||
|
||||
# On error
|
||||
return HttpResponse( 'Error: ' + str( e ) )
|
||||
|
||||
return wrap
|
||||
0
apps/dyn_api/migrations/__init__.py
Normal file
0
apps/dyn_api/migrations/__init__.py
Normal file
8
apps/dyn_api/tests.py
Normal file
8
apps/dyn_api/tests.py
Normal file
@@ -0,0 +1,8 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
16
apps/dyn_api/urls.py
Normal file
16
apps/dyn_api/urls.py
Normal file
@@ -0,0 +1,16 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
from apps.dyn_api import views
|
||||
|
||||
urlpatterns = [
|
||||
path('api/', views.index, name="dynamic_api"),
|
||||
|
||||
path('api/<str:model_name>/' , views.DynamicAPI.as_view(), name="model_api"),
|
||||
path('api/<str:model_name>/<str:id>' , views.DynamicAPI.as_view()),
|
||||
path('api/<str:model_name>/<str:id>/' , views.DynamicAPI.as_view()),
|
||||
]
|
||||
155
apps/dyn_api/views.py
Normal file
155
apps/dyn_api/views.py
Normal file
@@ -0,0 +1,155 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2019 - present AppSeed.us
|
||||
"""
|
||||
|
||||
from django.http import Http404
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
|
||||
from rest_framework.generics import get_object_or_404
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from django.http import HttpResponse
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
DYNAMIC_API = {}
|
||||
|
||||
try:
|
||||
DYNAMIC_API = getattr(settings, 'DYNAMIC_API')
|
||||
except:
|
||||
pass
|
||||
|
||||
from .helpers import Utils
|
||||
|
||||
def index(request):
|
||||
|
||||
context = {
|
||||
'routes' : settings.DYNAMIC_API.keys(),
|
||||
'segment': 'dynamic_api'
|
||||
}
|
||||
|
||||
return render(request, 'dyn_api/index.html', context)
|
||||
|
||||
class DynamicAPI(APIView):
|
||||
|
||||
# READ : GET api/model/id or api/model
|
||||
def get(self, request, **kwargs):
|
||||
|
||||
model_id = kwargs.get('id', None)
|
||||
try:
|
||||
if model_id is not None:
|
||||
|
||||
# Validate for integer
|
||||
try:
|
||||
model_id = int(model_id)
|
||||
|
||||
if model_id < 0:
|
||||
raise ValueError('Expect positive int')
|
||||
|
||||
except ValueError as e:
|
||||
return Response(data={
|
||||
'message': 'Input Error = ' + str(e),
|
||||
'success': False
|
||||
}, status=400)
|
||||
|
||||
thing = get_object_or_404(Utils.get_manager(DYNAMIC_API, kwargs.get('model_name')), id=model_id)
|
||||
model_serializer = Utils.get_serializer(DYNAMIC_API, kwargs.get('model_name'))(instance=thing)
|
||||
output = model_serializer.data
|
||||
else:
|
||||
all_things = Utils.get_manager(DYNAMIC_API, kwargs.get('model_name')).all()
|
||||
thing_serializer = Utils.get_serializer(DYNAMIC_API, kwargs.get('model_name'))
|
||||
output = []
|
||||
for thing in all_things:
|
||||
output.append(thing_serializer(instance=thing).data)
|
||||
except KeyError:
|
||||
return Response(data={
|
||||
'message': 'this model is not activated or not exist.',
|
||||
'success': False
|
||||
}, status=400)
|
||||
except Http404:
|
||||
return Response(data={
|
||||
'message': 'object with given id not found.',
|
||||
'success': False
|
||||
}, status=404)
|
||||
return Response(data={
|
||||
'data': output,
|
||||
'success': True
|
||||
}, status=200)
|
||||
|
||||
# CREATE : POST api/model/
|
||||
#@check_permission
|
||||
def post(self, request, **kwargs):
|
||||
try:
|
||||
model_serializer = Utils.get_serializer(DYNAMIC_API, kwargs.get('model_name'))(data=request.data)
|
||||
if model_serializer.is_valid():
|
||||
model_serializer.save()
|
||||
else:
|
||||
return Response(data={
|
||||
**model_serializer.errors,
|
||||
'success': False
|
||||
}, status=400)
|
||||
except KeyError:
|
||||
return Response(data={
|
||||
'message': 'this model is not activated or not exist.',
|
||||
'success': False
|
||||
}, status=400)
|
||||
return Response(data={
|
||||
'message': 'Record Created.',
|
||||
'success': True
|
||||
}, status=200)
|
||||
|
||||
# UPDATE : PUT api/model/id/
|
||||
#@check_permission
|
||||
def put(self, request, **kwargs):
|
||||
try:
|
||||
thing = get_object_or_404(Utils.get_manager(DYNAMIC_API, kwargs.get('model_name')), id=kwargs.get('id'))
|
||||
model_serializer = Utils.get_serializer(DYNAMIC_API, kwargs.get('model_name'))(instance=thing,
|
||||
data=request.data,
|
||||
partial=True)
|
||||
if model_serializer.is_valid():
|
||||
model_serializer.save()
|
||||
else:
|
||||
return Response(data={
|
||||
**model_serializer.errors,
|
||||
'success': False
|
||||
}, status=400)
|
||||
except KeyError:
|
||||
return Response(data={
|
||||
'message': 'this model is not activated or not exist.',
|
||||
'success': False
|
||||
}, status=400)
|
||||
except Http404:
|
||||
return Response(data={
|
||||
'message': 'object with given id not found.',
|
||||
'success': False
|
||||
}, status=404)
|
||||
return Response(data={
|
||||
'message': 'Record Updated.',
|
||||
'success': True
|
||||
}, status=200)
|
||||
|
||||
# DELETE : DELETE api/model/id/
|
||||
#@check_permission
|
||||
def delete(self, request, **kwargs):
|
||||
try:
|
||||
model_manager = Utils.get_manager(DYNAMIC_API, kwargs.get('model_name'))
|
||||
to_delete_id = kwargs.get('id')
|
||||
model_manager.get(id=to_delete_id).delete()
|
||||
except KeyError:
|
||||
return Response(data={
|
||||
'message': 'this model is not activated or not exist.',
|
||||
'success': False
|
||||
}, status=400)
|
||||
except Utils.get_class(DYNAMIC_API, kwargs.get('model_name')).DoesNotExist as e:
|
||||
return Response(data={
|
||||
'message': 'object with given id not found.',
|
||||
'success': False
|
||||
}, status=404)
|
||||
return Response(data={
|
||||
'message': 'Record Deleted.',
|
||||
'success': True
|
||||
}, status=200)
|
||||
Reference in New Issue
Block a user