sample api work

This commit is contained in:
mahdavi 2024-07-20 23:12:33 +03:30
parent 71685ebbad
commit b6a57bfc65
6 changed files with 71 additions and 0 deletions

0
apps/crud/__init__.py Normal file
View file

6
apps/crud/admin.py Normal file
View file

@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Plan, Data
admin.site.register(Data)
admin.site.register(Plan)

6
apps/crud/apps.py Normal file
View file

@ -0,0 +1,6 @@
from django.apps import AppConfig
class CrudConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.crud'

20
apps/crud/models.py Normal file
View file

@ -0,0 +1,20 @@
from django.db import models
from apps.gooyal_oauth2.models import Application
from apps.users.models import User
class Plan(models.Model):
application = models.ForeignKey(Application, on_delete=models.PROTECT)
client_id = models.CharField(max_length=255, null=True, blank=True)
owner = models.ForeignKey(User, on_delete=models.PROTECT)
record_count = models.IntegerField(default=0)
record_limit = models.IntegerField(default=0)
class Data(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
plan = models.ForeignKey(Plan, on_delete=models.PROTECT)
data = models.JSONField(default=dict)
class Meta:
unique_together = ('user', 'plan')

3
apps/crud/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

36
apps/crud/views.py Normal file
View file

@ -0,0 +1,36 @@
from django.http import Http404
from django.shortcuts import render
from oauth2_provider.contrib.rest_framework import TokenMatchesOASRequirements
from rest_framework import viewsets, mixins
from rest_framework.generics import get_object_or_404
from rest_framework.viewsets import GenericViewSet
from apps.crud.models import Data, Plan
from apps.crud.serializers import DataSerializer
from apps.gooyal_oauth2.rest_framework import IsAuthenticatedOrTokenMatchesOASRequirements
class DataViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericViewSet):
queryset = Data.objects.all()
serializer_class = DataSerializer
permission_classes = [IsAuthenticatedOrTokenMatchesOASRequirements]
required_alternate_scopes = {
"GET": [["data_crud.data:retrieve"]],
"PATCH": [["data_crud.data:update"]],
"PUT": [["data_crud.data:update"]],
"DELETE": [["data_crud.data:delete"]],
}
def get_object(self):
user = self.request.user
auth = self.request.auth
if auth:
plan = Plan.objects.filter(application_id=auth.application_id).first()
data, created = Data.objects.get_or_create(plan_id=plan.pk, user=user)
return data
raise Http404