diff --git a/LAB4/LAB4/__init__.py b/LAB4/LAB4/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/LAB4/LAB4/__pycache__/__init__.cpython-310.pyc b/LAB4/LAB4/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 00000000..5675447e Binary files /dev/null and b/LAB4/LAB4/__pycache__/__init__.cpython-310.pyc differ diff --git a/LAB4/LAB4/__pycache__/settings.cpython-310.pyc b/LAB4/LAB4/__pycache__/settings.cpython-310.pyc new file mode 100644 index 00000000..daba2104 Binary files /dev/null and b/LAB4/LAB4/__pycache__/settings.cpython-310.pyc differ diff --git a/LAB4/LAB4/__pycache__/urls.cpython-310.pyc b/LAB4/LAB4/__pycache__/urls.cpython-310.pyc new file mode 100644 index 00000000..1330797b Binary files /dev/null and b/LAB4/LAB4/__pycache__/urls.cpython-310.pyc differ diff --git a/LAB4/LAB4/__pycache__/wsgi.cpython-310.pyc b/LAB4/LAB4/__pycache__/wsgi.cpython-310.pyc new file mode 100644 index 00000000..22ddaf8c Binary files /dev/null and b/LAB4/LAB4/__pycache__/wsgi.cpython-310.pyc differ diff --git a/LAB4/LAB4/asgi.py b/LAB4/LAB4/asgi.py new file mode 100644 index 00000000..10d559d8 --- /dev/null +++ b/LAB4/LAB4/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for LAB4 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/4.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LAB4.settings') + +application = get_asgi_application() diff --git a/LAB4/LAB4/settings.py b/LAB4/LAB4/settings.py new file mode 100644 index 00000000..9f5476ff --- /dev/null +++ b/LAB4/LAB4/settings.py @@ -0,0 +1,125 @@ +""" +Django settings for LAB4 project. + +Generated by 'django-admin startproject' using Django 4.0.6. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.0/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/4.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-ts05**w9$68e^qmf&tt-l&ys%jr6&nz=dvl_9or6pxfa9peo9k' + +# 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', + 'orm' +] + +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 = 'LAB4.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 = 'LAB4.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/LAB4/LAB4/urls.py b/LAB4/LAB4/urls.py new file mode 100644 index 00000000..b9ef90e4 --- /dev/null +++ b/LAB4/LAB4/urls.py @@ -0,0 +1,23 @@ +"""LAB4 URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.0/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('brand/', include('orm.urls')) +] diff --git a/LAB4/LAB4/wsgi.py b/LAB4/LAB4/wsgi.py new file mode 100644 index 00000000..68bbdb37 --- /dev/null +++ b/LAB4/LAB4/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for LAB4 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/4.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LAB4.settings') + +application = get_wsgi_application() diff --git a/LAB4/db.sqlite3 b/LAB4/db.sqlite3 new file mode 100644 index 00000000..f86ddcb3 Binary files /dev/null and b/LAB4/db.sqlite3 differ diff --git a/LAB4/manage.py b/LAB4/manage.py new file mode 100644 index 00000000..9e123e7a --- /dev/null +++ b/LAB4/manage.py @@ -0,0 +1,22 @@ +#!/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', 'LAB4.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() diff --git a/LAB4/orm/__init__.py b/LAB4/orm/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/LAB4/orm/__pycache__/__init__.cpython-310.pyc b/LAB4/orm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 00000000..741904bb Binary files /dev/null and b/LAB4/orm/__pycache__/__init__.cpython-310.pyc differ diff --git a/LAB4/orm/__pycache__/admin.cpython-310.pyc b/LAB4/orm/__pycache__/admin.cpython-310.pyc new file mode 100644 index 00000000..9ad3e634 Binary files /dev/null and b/LAB4/orm/__pycache__/admin.cpython-310.pyc differ diff --git a/LAB4/orm/__pycache__/apps.cpython-310.pyc b/LAB4/orm/__pycache__/apps.cpython-310.pyc new file mode 100644 index 00000000..e199d286 Binary files /dev/null and b/LAB4/orm/__pycache__/apps.cpython-310.pyc differ diff --git a/LAB4/orm/__pycache__/models.cpython-310.pyc b/LAB4/orm/__pycache__/models.cpython-310.pyc new file mode 100644 index 00000000..7bfb7149 Binary files /dev/null and b/LAB4/orm/__pycache__/models.cpython-310.pyc differ diff --git a/LAB4/orm/__pycache__/serializers.cpython-310.pyc b/LAB4/orm/__pycache__/serializers.cpython-310.pyc new file mode 100644 index 00000000..13efaabb Binary files /dev/null and b/LAB4/orm/__pycache__/serializers.cpython-310.pyc differ diff --git a/LAB4/orm/__pycache__/urls.cpython-310.pyc b/LAB4/orm/__pycache__/urls.cpython-310.pyc new file mode 100644 index 00000000..2e2631f4 Binary files /dev/null and b/LAB4/orm/__pycache__/urls.cpython-310.pyc differ diff --git a/LAB4/orm/__pycache__/views.cpython-310.pyc b/LAB4/orm/__pycache__/views.cpython-310.pyc new file mode 100644 index 00000000..ff4f9ee0 Binary files /dev/null and b/LAB4/orm/__pycache__/views.cpython-310.pyc differ diff --git a/LAB4/orm/admin.py b/LAB4/orm/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/LAB4/orm/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/LAB4/orm/apps.py b/LAB4/orm/apps.py new file mode 100644 index 00000000..54bea84e --- /dev/null +++ b/LAB4/orm/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class OrmConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'orm' diff --git a/LAB4/orm/migrations/0001_initial.py b/LAB4/orm/migrations/0001_initial.py new file mode 100644 index 00000000..c1a52708 --- /dev/null +++ b/LAB4/orm/migrations/0001_initial.py @@ -0,0 +1,38 @@ +# Generated by Django 4.0.6 on 2022-07-31 16:18 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Brand', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('description', models.TextField()), + ('established_at', models.DateField()), + ('city', models.CharField(max_length=50)), + ], + ), + migrations.CreateModel( + name='Product', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=40)), + ('description', models.TextField()), + ('image_url', models.URLField()), + ('price', models.FloatField()), + ('quantity', models.IntegerField()), + ('is_active', models.BooleanField()), + ('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orm.brand')), + ], + ), + ] diff --git a/LAB4/orm/migrations/__init__.py b/LAB4/orm/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/LAB4/orm/migrations/__pycache__/0001_initial.cpython-310.pyc b/LAB4/orm/migrations/__pycache__/0001_initial.cpython-310.pyc new file mode 100644 index 00000000..d79b11f3 Binary files /dev/null and b/LAB4/orm/migrations/__pycache__/0001_initial.cpython-310.pyc differ diff --git a/LAB4/orm/migrations/__pycache__/__init__.cpython-310.pyc b/LAB4/orm/migrations/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 00000000..4adc9bda Binary files /dev/null and b/LAB4/orm/migrations/__pycache__/__init__.cpython-310.pyc differ diff --git a/LAB4/orm/models.py b/LAB4/orm/models.py new file mode 100644 index 00000000..06e5949d --- /dev/null +++ b/LAB4/orm/models.py @@ -0,0 +1,20 @@ +from django.db import models + + +# Create your models here. + +class Brand(models.Model): + title = models.CharField(max_length=50) + description = models.TextField() + established_at = models.DateField() + city = models.CharField(max_length=50) + + +class Product(models.Model): + brand = models.ForeignKey(Brand, on_delete=models.CASCADE) + name = models.CharField(max_length=40) + description = models.TextField() + image_url = models.URLField() + price = models.FloatField() + quantity = models.IntegerField() + is_active = models.BooleanField() diff --git a/LAB4/orm/serializers.py b/LAB4/orm/serializers.py new file mode 100644 index 00000000..ee1fd348 --- /dev/null +++ b/LAB4/orm/serializers.py @@ -0,0 +1,19 @@ +from dataclasses import field, fields +from rest_framework import serializers + +from .models import Brand, Product + + +class BrandSerializer(serializers.ModelSerializer): + + class Meta: + model = Brand + fields = '__all__' + + +class ProductSerializer(serializers.ModelSerializer): + + class Meta: + model = Product + fields = '__all__' + diff --git a/LAB4/orm/tests.py b/LAB4/orm/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/LAB4/orm/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/LAB4/orm/urls.py b/LAB4/orm/urls.py new file mode 100644 index 00000000..e37c0495 --- /dev/null +++ b/LAB4/orm/urls.py @@ -0,0 +1,17 @@ +from django.urls import path +from . import views + +app_name = 'orm' + +urlpatterns = [ + path('add/', views.add_brand, name='add_brand'), + path('list/', views.list_brand, name='list_brand'), + path('update//', views.update_brand, name='update_brand'), + path('delete//', views.remove_brand , name='remove_brand'), + path('search/', views.search_brand, name='search_brand'), + path('products/add/', views.add_product, name='add_product'), + path('products/list/', views.list_product, name='list_products'), + path('products/update//', views.update_product, name='update_product'), + path('products/delete//', views.delete_product, name='delete_product'), + path('products/specified_list/', views.list_products_of_brand, name='list products of brand') +] \ No newline at end of file diff --git a/LAB4/orm/views.py b/LAB4/orm/views.py new file mode 100644 index 00000000..1b2105a5 --- /dev/null +++ b/LAB4/orm/views.py @@ -0,0 +1,168 @@ +from turtle import title +from django.urls import is_valid_path +from rest_framework.decorators import api_view +from rest_framework.request import Request +from rest_framework.response import Response +from .models import Brand, Product +from .serializers import BrandSerializer, ProductSerializer +from rest_framework import status + +# Create your views here. + + # ------------------- CRUD Process For Brand ----------------------- # + +# ----------------------- Add Brand ---------------------------# + +@api_view(['POST']) +def add_brand(request : Request): + + brand_serializer = BrandSerializer(data=request.data) + + if brand_serializer.is_valid(): + brand_serializer.save() + else: + return Response({'msg' : 'could not add a brand', 'errors': brand_serializer.errors}, status=status.HTTP_403_FORBIDDEN) + + + return Response({'msg' : 'brand added successfully!'}, status=status.HTTP_201_CREATED) + +# ---------------------------- List All Brands ------------------- # + +@api_view(['GET']) +def list_brand(request: Request): + + skip = int(request.query_params.get('skip',0)) + get = int(request.query_params.get('get', 3)) + + brands = Brand.objects.all() + brands_list = BrandSerializer(instance=brands, many=True).data[skip:get] #.data to convert object of serializer to json obj. + + return Response({'msg' : 'List of all brands!', 'brands' : brands_list}) + +# ------------------------ Update a Brand ---------------------- # + +@api_view(['PUT']) +def update_brand(request: Request, brand_id): + + try: + brand = Brand.objects.get(id=brand_id) + except Exception as e: + return Response({'msg' : 'brand not found'}, status=status.HTTP_404_NOT_FOUND) + + brand_updated = BrandSerializer(instance=brand, data=request.data) + + if brand_updated.is_valid(): + brand_updated.save() + else: + return Response({'msg' : 'could not update a brand!', 'errors': BrandSerializer.errors}, status=status.HTTP_403_FORBIDDEN) + + return Response({'msg' : 'a brand updated successfully!'}, status=status.HTTP_202_ACCEPTED) + +# ---------------------------- Delete a Brand ------------------- # + +@api_view(['DELETE']) +def remove_brand(request: Request, brand_id): + + try: + brand = Brand.objects.get(id=brand_id) + brand.delete() + except Exception as e: + return Response({'msg' : 'could not find a brand!'}, status=status.HTTP_404_NOT_FOUND) + + + return Response({'msg' : 'brand deleted successfully!'}, status=status.HTTP_302_FOUND) + +@api_view(['GET']) +def search_brand(request: Request): + + if 'search' in request.query_params: + search_phrase = request.query_params['search'] + brand = Brand.objects.filter(title__contains=search_phrase).all() + + else: + return Response({'msg' : 'No brand found!'}) + + brand_found = BrandSerializer(instance=brand, many=True).data + + return Response({'msg': 'Brand found!', 'brand' : brand_found}) + + + + + #--------------------------- CRUD Process For Product ----------------- # + +# ---------------------------- Add Product --------------------------- # + +@api_view(['POST']) +def add_product(request: Request): + + product_serializer = ProductSerializer(data=request.data) + + if product_serializer.is_valid(): + product_serializer.save() + else: + return Response({'msg' : 'could not add a product', 'errors': ProductSerializer.errors}, status=status.HTTP_403_FORBIDDEN) + + return Response({'msg': 'product added successfully!'}, status=status.HTTP_201_CREATED) + +# ------------------------------ List All Products ------------------------ # + +@api_view(['GET']) +def list_product(request: Request): + + skip = int(request.query_params.get('skip',0)) + get = int(request.query_params.get('get', 3)) + + products = Product.objects.all() + product_list = ProductSerializer(instance=products, many=True).data[skip:get] #.data to convert list of Serializer obj to JSON obj + + return Response({'msg' : 'List of products', 'products': product_list}, status=status.HTTP_200_OK) + +# --------------------------- Update a Product -------------------------- # + +@api_view(['PUT']) +def update_product(request: Request, product_id): + + try: + product = Product.objects.get(id=product_id) + except Exception as e: + return Response({'msg' : 'could not find a product1'}, status=status.HTTP_404_NOT_FOUND) + + product_updated = ProductSerializer(instance=product, data=request.data) + + if product_updated.is_valid(): + product_updated.save() + else: + return Response({'msg' : 'could not update a product!', 'errors' : ProductSerializer.errors}, status=status.HTTP_403_FORBIDDEN) + + return Response({'msg' : 'product updated successfully!'}, status=status.HTTP_202_ACCEPTED) + + +# -------------------------- Delete a product ----------------------- # + +@api_view(['DELETE']) +def delete_product(request: Request, product_id): + + try: + product = Product.objects.get(id=product_id) + product.delete() + except Exception as e: + return Response({'msg' : 'could not find a product'}, status=status.HTTP_404_NOT_FOUND) + + return Response({'msg' : 'product deleted successfull!'}, status=status.HTTP_202_ACCEPTED) + +@api_view(['GET']) +def list_products_of_brand(request: Request): + + if 'search' in request.query_params: + search_id = int(request.query_params.get('search')) + all_products = Product.objects.filter(brand_id=search_id) + else: + return Response({'msg' : 'No products found for this brand!'})# This doesn't appear when there are no products in a given brand + + products = ProductSerializer(instance=all_products, many=True).data + + return Response({'msg': 'list products of specific brand', 'products': products}) + + +