├── backend ├── __init__.py ├── core │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── 0001_initial.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── urls.py │ ├── tests.py │ └── views.py ├── urls.py ├── asgi.py ├── wsgi.py └── settings.py ├── requirements.txt ├── manage.py ├── contrib └── env_gen.py ├── README.md └── .gitignore /backend/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backend/core/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backend/core/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==3.2.* 2 | django-extensions==3.1.5 3 | python-decouple==3.5 4 | -------------------------------------------------------------------------------- /backend/core/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import Video 4 | 5 | admin.site.register(Video) 6 | -------------------------------------------------------------------------------- /backend/core/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class CoreConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'backend.core' 7 | -------------------------------------------------------------------------------- /backend/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import include, path 3 | 4 | urlpatterns = [ 5 | path('', include('backend.core.urls', namespace='core')), 6 | path('admin/', admin.site.urls), 7 | ] 8 | -------------------------------------------------------------------------------- /backend/core/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from .models import Video 4 | 5 | 6 | class VideoForm(forms.ModelForm): 7 | 8 | class Meta: 9 | model = Video 10 | fields = ('title', 'link', 'view') 11 | -------------------------------------------------------------------------------- /backend/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for backend project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /backend/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for backend project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /backend/core/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Video(models.Model): 5 | title = models.CharField('título', max_length=30) 6 | link = models.URLField(null=True, blank=True) 7 | view = models.IntegerField('visualização', default=0, null=True, blank=True) 8 | 9 | class Meta: 10 | ordering = ('id',) 11 | verbose_name = 'vídeo' 12 | verbose_name_plural = 'vídeos' 13 | 14 | def __str__(self): 15 | return f'{self.title}' 16 | 17 | def to_dict(self): 18 | return { 19 | 'id': self.id, 20 | 'title': self.title, 21 | 'link': self.link, 22 | 'view': self.view, 23 | } 24 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /backend/core/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import include, path 2 | 3 | from backend.core import views as v 4 | 5 | app_name = 'core' 6 | 7 | v1_urlpatterns = [ 8 | path('videos/', v.video_list, name='video_list'), 9 | path('videos//', v.video_detail, name='video_detail'), 10 | path('videos/create/', v.video_create, name='video_create'), 11 | path('videos//update/', v.video_update, name='video_update'), 12 | path('videos//delete/', v.video_delete, name='video_delete'), 13 | ] 14 | 15 | v2_urlpatterns = [ 16 | path('videos/', v.videos, name='videos'), 17 | path('videos//', v.video, name='video'), 18 | ] 19 | 20 | urlpatterns = [ 21 | path('api/v1/', include(v1_urlpatterns)), 22 | path('api/v2/', include(v2_urlpatterns)), 23 | ] 24 | -------------------------------------------------------------------------------- /backend/core/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.9 on 2021-11-21 04:49 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Video', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('title', models.CharField(max_length=30, verbose_name='título')), 19 | ('link', models.URLField(blank=True, null=True)), 20 | ('view', models.IntegerField(blank=True, default=0, null=True, verbose_name='visualização')), 21 | ], 22 | options={ 23 | 'verbose_name': 'vídeo', 24 | 'verbose_name_plural': 'vídeos', 25 | 'ordering': ('id',), 26 | }, 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /contrib/env_gen.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python SECRET_KEY generator. 3 | """ 4 | import random 5 | 6 | chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!?@#$%^&*()" 7 | size = 50 8 | secret_key = "".join(random.sample(chars, size)) 9 | 10 | chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!?@#$%_" 11 | size = 20 12 | password = "".join(random.sample(chars, size)) 13 | 14 | CONFIG_STRING = """ 15 | DEBUG=True 16 | SECRET_KEY=%s 17 | ALLOWED_HOSTS=127.0.0.1,.localhost,0.0.0.0 18 | 19 | #DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME 20 | #POSTGRES_DB= 21 | #POSTGRES_USER= 22 | #POSTGRES_PASSWORD=%s 23 | #DB_HOST=localhost 24 | 25 | #DEFAULT_FROM_EMAIL= 26 | #EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend 27 | #EMAIL_HOST=localhost 28 | #EMAIL_PORT= 29 | #EMAIL_HOST_USER= 30 | #EMAIL_HOST_PASSWORD= 31 | #EMAIL_USE_TLS=True 32 | """.strip() % (secret_key, password) 33 | 34 | # Writing our configuration file to '.env' 35 | with open('.env', 'w') as configfile: 36 | configfile.write(CONFIG_STRING) 37 | 38 | print('Success!') 39 | print('Type: cat .env') 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django API without DRF 2 | 3 | This is a API project made with Django, and without Django REST framework. 4 | 5 | ## This project was done with: 6 | 7 | * [Python 3.9.8](https://www.python.org/) 8 | * [Django 3.2.10](https://www.djangoproject.com/) 9 | 10 | ## How to run project? 11 | 12 | * Clone this repository. 13 | * Create virtualenv with Python 3. 14 | * Active the virtualenv. 15 | * Install dependences. 16 | * Run the migrations. 17 | 18 | ``` 19 | git clone https://github.com/rg3915/django-api-without-drf.git 20 | cd django-api-without-drf 21 | python -m venv .venv 22 | source .venv/bin/activate 23 | pip install -r requirements.txt 24 | python contrib/env_gen.py 25 | python manage.py migrate 26 | python manage.py createsuperuser --username="admin" --email="" 27 | ``` 28 | 29 | ## endpoints 30 | 31 | ``` 32 | /api/v1/videos/ backend.core.views.video_list core:video_list 33 | /api/v1/videos// backend.core.views.video_detail core:video_detail 34 | /api/v1/videos//delete/ backend.core.views.video_delete core:video_delete 35 | /api/v1/videos//update/ backend.core.views.video_update core:video_update 36 | /api/v1/videos/create/ backend.core.views.video_create core:video_create 37 | /api/v2/videos/ backend.core.views.videos core:videos 38 | /api/v2/videos// backend.core.views.video core:video 39 | ``` 40 | 41 | ## Examples with httpie 42 | 43 | ``` 44 | pip install httpie 45 | ``` 46 | 47 | ### Adiciona vídeo 48 | 49 | ``` 50 | http POST http://localhost:8000/api/v2/videos/ \ 51 | title="Dica #49 - DRF: Autenticação via JWT com djoser - Django REST framework" \ 52 | link="https://youtu.be/dOomllYxj9E" \ 53 | view=198 54 | 55 | http POST http://localhost:8000/api/v2/videos/ \ 56 | title="Dica #50 - DRF: Django CORS headers + Login com VueJS" \ 57 | link="https://youtu.be/2SyQ9xXdMvw" \ 58 | view=171 59 | ``` 60 | 61 | ### Lista vídeos 62 | 63 | ``` 64 | http http://localhost:8000/api/v2/videos/ 65 | ``` 66 | 67 | ### Visualiza um vídeo 68 | 69 | ``` 70 | http http://localhost:8000/api/v2/videos/1/ 71 | ``` 72 | 73 | ### Edita um vídeo 74 | 75 | ``` 76 | http POST http://localhost:8000/api/v2/videos/1/ \ 77 | title="Dica #49 - DRF: Autenticação via JWT com djoser" 78 | ``` 79 | 80 | ### Deleta um vídeo 81 | 82 | ``` 83 | http DELETE http://localhost:8000/api/v2/videos/1/ 84 | ``` 85 | 86 | 87 | ## TDD 88 | 89 | https://github.com/rg3915/django-api-without-drf/blob/main/backend/core/tests.py 90 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .DS_Store 132 | 133 | media/ 134 | staticfiles/ 135 | .idea 136 | .ipynb_checkpoints/ 137 | .vscode 138 | -------------------------------------------------------------------------------- /backend/core/tests.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.test import TestCase 4 | 5 | from .models import Video 6 | 7 | 8 | class VideoTest(TestCase): 9 | 10 | def setUp(self): 11 | self.payload = { 12 | "title": "Dica #47 - DRF: djoser - Django REST framework", 13 | "link": "https://youtu.be/HUtG2Eg47Gw", 14 | "view": 307 15 | } 16 | 17 | def test_video_create(self): 18 | response = self.client.post( 19 | '/api/v2/videos/', 20 | data=self.payload, 21 | content_type='application/json' 22 | ) 23 | resultado = json.loads(response.content) 24 | esperado = { 25 | "data": { 26 | "id": 1, 27 | **self.payload 28 | } 29 | } 30 | self.assertEqual(esperado, resultado) 31 | 32 | def test_video_list(self): 33 | Video.objects.create(**self.payload) 34 | 35 | response = self.client.get( 36 | '/api/v2/videos/', 37 | content_type='application/json' 38 | ) 39 | resultado = json.loads(response.content) 40 | esperado = { 41 | "data": [ 42 | { 43 | "id": 1, 44 | **self.payload 45 | } 46 | ] 47 | } 48 | self.assertEqual(esperado, resultado) 49 | 50 | def test_video_detail(self): 51 | Video.objects.create(**self.payload) 52 | 53 | response = self.client.get( 54 | '/api/v2/videos/1/', 55 | content_type='application/json' 56 | ) 57 | resultado = json.loads(response.content) 58 | esperado = { 59 | "data": { 60 | "id": 1, 61 | **self.payload 62 | } 63 | } 64 | self.assertEqual(esperado, resultado) 65 | 66 | def test_video_update(self): 67 | Video.objects.create(**self.payload) 68 | 69 | data = { 70 | "title": "Dica #47 - DRF: djoser" 71 | } 72 | 73 | response = self.client.post( 74 | '/api/v2/videos/1/', 75 | data=data, 76 | content_type='application/json' 77 | ) 78 | resultado = json.loads(response.content) 79 | esperado = { 80 | "data": 81 | { 82 | "id": 1, 83 | "title": "Dica #47 - DRF: djoser", 84 | "link": "https://youtu.be/HUtG2Eg47Gw", 85 | "view": 307 86 | } 87 | } 88 | self.assertEqual(esperado, resultado) 89 | 90 | def test_video_delete(self): 91 | Video.objects.create(**self.payload) 92 | 93 | response = self.client.delete( 94 | '/api/v2/videos/1/', 95 | content_type='application/json' 96 | ) 97 | resultado = json.loads(response.content) 98 | esperado = {"data": "Item deletado com sucesso."} 99 | 100 | self.assertEqual(esperado, resultado) 101 | -------------------------------------------------------------------------------- /backend/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for backend project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.9. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | from decouple import Csv, config 16 | 17 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 18 | BASE_DIR = Path(__file__).resolve().parent.parent 19 | 20 | 21 | # Quick-start development settings - unsuitable for production 22 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 23 | 24 | # SECURITY WARNING: keep the secret key used in production secret! 25 | SECRET_KEY = config('SECRET_KEY') 26 | 27 | # SECURITY WARNING: don't run with debug turned on in production! 28 | DEBUG = config('DEBUG', default=False, cast=bool) 29 | 30 | ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) 31 | 32 | 33 | # Application definition 34 | 35 | INSTALLED_APPS = [ 36 | 'django.contrib.admin', 37 | 'django.contrib.auth', 38 | 'django.contrib.contenttypes', 39 | 'django.contrib.sessions', 40 | 'django.contrib.messages', 41 | 'django.contrib.staticfiles', 42 | 'django_extensions', 43 | 'backend.core', 44 | ] 45 | 46 | MIDDLEWARE = [ 47 | 'django.middleware.security.SecurityMiddleware', 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.common.CommonMiddleware', 50 | 'django.middleware.csrf.CsrfViewMiddleware', 51 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | ] 55 | 56 | ROOT_URLCONF = 'backend.urls' 57 | 58 | TEMPLATES = [ 59 | { 60 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 61 | 'DIRS': [], 62 | 'APP_DIRS': True, 63 | 'OPTIONS': { 64 | 'context_processors': [ 65 | 'django.template.context_processors.debug', 66 | 'django.template.context_processors.request', 67 | 'django.contrib.auth.context_processors.auth', 68 | 'django.contrib.messages.context_processors.messages', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'backend.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.db.backends.sqlite3', 83 | 'NAME': BASE_DIR / 'db.sqlite3', 84 | } 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | 107 | # Internationalization 108 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 109 | 110 | LANGUAGE_CODE = 'pt-br' 111 | 112 | TIME_ZONE = 'America/Sao_Paulo' 113 | 114 | USE_I18N = True 115 | 116 | USE_L10N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | # Static files (CSS, JavaScript, Images) 122 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 123 | 124 | STATIC_URL = '/static/' 125 | 126 | # Default primary key field type 127 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 128 | 129 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 130 | -------------------------------------------------------------------------------- /backend/core/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.http import JsonResponse 4 | from django.shortcuts import get_object_or_404 5 | from django.views.decorators.csrf import csrf_exempt 6 | from django.views.decorators.http import require_http_methods 7 | 8 | from .forms import VideoForm 9 | from .models import Video 10 | 11 | 12 | @require_http_methods(['GET']) 13 | def video_list(request): 14 | videos = Video.objects.all() 15 | data = [video.to_dict() for video in videos] 16 | return JsonResponse({'data': data}) 17 | 18 | 19 | @require_http_methods(['GET']) 20 | def video_detail(request, pk): 21 | video = Video.objects.get(pk=pk) 22 | data = video.to_dict() 23 | return JsonResponse({'data': data}) 24 | 25 | 26 | @csrf_exempt 27 | @require_http_methods(['POST']) 28 | def video_create(request): 29 | form = VideoForm(request.POST or None) 30 | 31 | if request.POST: 32 | # Dados obtidos pelo formulário. 33 | if form.is_valid(): 34 | video = form.save() 35 | 36 | elif request.body: 37 | # Dados obtidos via json. 38 | data = json.loads(request.body) 39 | video = Video.objects.create(**data) 40 | 41 | else: 42 | return JsonResponse({'message': 'Algo deu errado.'}) 43 | 44 | return JsonResponse({'data': video.to_dict()}) 45 | 46 | 47 | @csrf_exempt 48 | @require_http_methods(['POST']) # Não aceita PUT 49 | def video_update(request, pk): 50 | video = get_object_or_404(Video, pk=pk) 51 | form = VideoForm(request.POST or None, instance=video) 52 | 53 | if request.POST: 54 | # Dados obtidos pelo formulário. 55 | if form.is_valid(): 56 | video = form.save() 57 | 58 | elif request.body: 59 | # Dados obtidos via json. 60 | data = json.loads(request.body) 61 | 62 | for attr, value in data.items(): 63 | setattr(video, attr, value) 64 | video.save() 65 | 66 | else: 67 | return JsonResponse({'message': 'Algo deu errado.'}) 68 | 69 | return JsonResponse({'data': video.to_dict()}) 70 | 71 | 72 | @csrf_exempt 73 | @require_http_methods(['DELETE']) 74 | def video_delete(request, pk): 75 | video = get_object_or_404(Video, pk=pk) 76 | video.delete() 77 | return JsonResponse({'data': 'Item deletado com sucesso.'}) 78 | 79 | 80 | @csrf_exempt 81 | def videos(request): 82 | videos = Video.objects.all() 83 | data = [video.to_dict() for video in videos] 84 | form = VideoForm(request.POST or None) 85 | 86 | if request.method == 'POST': 87 | if request.POST: 88 | # Dados obtidos pelo formulário. 89 | if form.is_valid(): 90 | video = form.save() 91 | 92 | elif request.body: 93 | # Dados obtidos via json. 94 | data = json.loads(request.body) 95 | video = Video.objects.create(**data) 96 | 97 | else: 98 | return JsonResponse({'message': 'Algo deu errado.'}) 99 | 100 | return JsonResponse({'data': video.to_dict()}) 101 | 102 | return JsonResponse({'data': data}) 103 | 104 | 105 | @csrf_exempt 106 | def video(request, pk): 107 | video = get_object_or_404(Video, pk=pk) 108 | form = VideoForm(request.POST or None, instance=video) 109 | 110 | if request.method == 'GET': 111 | data = video.to_dict() 112 | return JsonResponse({'data': data}) 113 | 114 | if request.method == 'POST': 115 | if request.POST: 116 | # Dados obtidos pelo formulário. 117 | if form.is_valid(): 118 | video = form.save() 119 | 120 | elif request.body: 121 | # Dados obtidos via json. 122 | data = json.loads(request.body) 123 | 124 | for attr, value in data.items(): 125 | setattr(video, attr, value) 126 | video.save() 127 | 128 | else: 129 | return JsonResponse({'message': 'Algo deu errado.'}) 130 | 131 | return JsonResponse({'data': video.to_dict()}) 132 | 133 | if request.method == 'DELETE': 134 | video.delete() 135 | return JsonResponse({'data': 'Item deletado com sucesso.'}) 136 | --------------------------------------------------------------------------------