From 57c22d254f5ab17ceddba9449ed9b5fa1d4936d5 Mon Sep 17 00:00:00 2001 From: Moritz Ellerbrock Date: Tue, 16 May 2023 10:54:33 +0200 Subject: [PATCH 1/2] add gitignore for django python project --- bookstore-django-py/.gitignore | 278 +++++++++++++++++++++++++++++++++ 1 file changed, 278 insertions(+) create mode 100644 bookstore-django-py/.gitignore diff --git a/bookstore-django-py/.gitignore b/bookstore-django-py/.gitignore new file mode 100644 index 0000000..bc88b61 --- /dev/null +++ b/bookstore-django-py/.gitignore @@ -0,0 +1,278 @@ +# Created by https://www.toptal.com/developers/gitignore/api/venv,python,django +# Edit at https://www.toptal.com/developers/gitignore?templates=venv,python,django + +### Django ### +*.log +*.pot +*.pyc +__pycache__/ +local_settings.py +db.sqlite3 +db.sqlite3-journal +media + +# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ +# in your Git repository. Update and uncomment the following line accordingly. +# /staticfiles/ + +### Django.Python Stack ### +# Byte-compiled / optimized / DLL files +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo + +# Django stuff: + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ + +### Python ### +# Byte-compiled / optimized / DLL files + +# C extensions + +# Distribution / packaging + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. + +# Installer logs + +# Unit test / coverage reports + +# Translations + +# Django stuff: + +# Flask stuff: + +# Scrapy stuff: + +# Sphinx documentation + +# PyBuilder + +# Jupyter Notebook + +# IPython + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm + +# Celery stuff + +# SageMath parsed files + +# Environments + +# Spyder project settings + +# Rope project settings + +# mkdocs documentation + +# mypy + +# Pyre type checker + +# pytype static type analyzer + +# Cython debug symbols + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +### venv ### +# Virtualenv +# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ +[Bb]in +[Ii]nclude +[Ll]ib +[Ll]ib64 +[Ll]ocal +[Ss]cripts +pyvenv.cfg +pip-selfcheck.json + +# End of https://www.toptal.com/developers/gitignore/api/venv,python,django \ No newline at end of file From 3030b7e58675cfab3aa7fc9c900518bd7d1b3fad Mon Sep 17 00:00:00 2001 From: Moritz Ellerbrock Date: Tue, 16 May 2023 11:16:05 +0200 Subject: [PATCH 2/2] add initial django implementation --- bookstore-django-py/books/__init__.py | 0 bookstore-django-py/books/admin.py | 3 + bookstore-django-py/books/apps.py | 6 + .../books/migrations/0001_initial.py | 24 ++++ .../books/migrations/0002_book_test.py | 19 +++ .../books/migrations/__init__.py | 0 bookstore-django-py/books/models.py | 12 ++ bookstore-django-py/books/serializers.py | 7 + bookstore-django-py/books/tests.py | 3 + bookstore-django-py/books/views.py | 55 ++++++++ .../bookstore_django_py/__init__.py | 0 .../bookstore_django_py/asgi.py | 16 +++ .../bookstore_django_py/settings.py | 128 ++++++++++++++++++ .../bookstore_django_py/urls.py | 24 ++++ .../bookstore_django_py/wsgi.py | 16 +++ bookstore-django-py/manage.py | 22 +++ 16 files changed, 335 insertions(+) create mode 100644 bookstore-django-py/books/__init__.py create mode 100644 bookstore-django-py/books/admin.py create mode 100644 bookstore-django-py/books/apps.py create mode 100644 bookstore-django-py/books/migrations/0001_initial.py create mode 100644 bookstore-django-py/books/migrations/0002_book_test.py create mode 100644 bookstore-django-py/books/migrations/__init__.py create mode 100644 bookstore-django-py/books/models.py create mode 100644 bookstore-django-py/books/serializers.py create mode 100644 bookstore-django-py/books/tests.py create mode 100644 bookstore-django-py/books/views.py create mode 100644 bookstore-django-py/bookstore_django_py/__init__.py create mode 100644 bookstore-django-py/bookstore_django_py/asgi.py create mode 100644 bookstore-django-py/bookstore_django_py/settings.py create mode 100644 bookstore-django-py/bookstore_django_py/urls.py create mode 100644 bookstore-django-py/bookstore_django_py/wsgi.py create mode 100755 bookstore-django-py/manage.py diff --git a/bookstore-django-py/books/__init__.py b/bookstore-django-py/books/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bookstore-django-py/books/admin.py b/bookstore-django-py/books/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/bookstore-django-py/books/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/bookstore-django-py/books/apps.py b/bookstore-django-py/books/apps.py new file mode 100644 index 0000000..a53388c --- /dev/null +++ b/bookstore-django-py/books/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class BooksConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'books' diff --git a/bookstore-django-py/books/migrations/0001_initial.py b/bookstore-django-py/books/migrations/0001_initial.py new file mode 100644 index 0000000..66ed16d --- /dev/null +++ b/bookstore-django-py/books/migrations/0001_initial.py @@ -0,0 +1,24 @@ +# Generated by Django 4.2.1 on 2023-05-14 08:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Book', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=255)), + ('author', models.CharField(max_length=255)), + ('release_date', models.DateField()), + ('publisher', models.CharField(max_length=255)), + ], + ), + ] diff --git a/bookstore-django-py/books/migrations/0002_book_test.py b/bookstore-django-py/books/migrations/0002_book_test.py new file mode 100644 index 0000000..e964030 --- /dev/null +++ b/bookstore-django-py/books/migrations/0002_book_test.py @@ -0,0 +1,19 @@ +# Generated by Django 4.2.1 on 2023-05-14 09:06 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('books', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='book', + name='test', + field=models.CharField(default='test', max_length=255), + preserve_default=False, + ), + ] diff --git a/bookstore-django-py/books/migrations/__init__.py b/bookstore-django-py/books/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bookstore-django-py/books/models.py b/bookstore-django-py/books/models.py new file mode 100644 index 0000000..1bd0f88 --- /dev/null +++ b/bookstore-django-py/books/models.py @@ -0,0 +1,12 @@ +from django.db import models + + +class Book(models.Model): + title = models.CharField(max_length=255) + author = models.CharField(max_length=255) + publisher = models.CharField(max_length=255) + release_date = models.DateField() + test = models.CharField(max_length=255) + + def __str__(self): + return self.title diff --git a/bookstore-django-py/books/serializers.py b/bookstore-django-py/books/serializers.py new file mode 100644 index 0000000..e424ee6 --- /dev/null +++ b/bookstore-django-py/books/serializers.py @@ -0,0 +1,7 @@ +from rest_framework import serializers +from .models import Book + +class BookSerializer(serializers.ModelSerializer): + class Meta: + model = Book + fields = ['id', 'title', 'author', 'release_date', 'publisher'] \ No newline at end of file diff --git a/bookstore-django-py/books/tests.py b/bookstore-django-py/books/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/bookstore-django-py/books/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/bookstore-django-py/books/views.py b/bookstore-django-py/books/views.py new file mode 100644 index 0000000..4a26ba5 --- /dev/null +++ b/bookstore-django-py/books/views.py @@ -0,0 +1,55 @@ +from django.shortcuts import get_object_or_404 +from django.http import JsonResponse +from django.views import View +from django.db import IntegrityError + +from .models import Book +import json + + +class BookList(View): + def get(self, request): + limit = request.GET.get('limit', None) + if limit: + books = Book.objects.all()[:int(limit)] + else: + books = Book.objects.all() + response_data = {"books": list(books.values())} + return JsonResponse(response_data) + + def post(self, request): + data = json.loads(request.body) + try: + book = Book.objects.create( + title=data['title'], + author=data['author'], + release_date=data['release_date'], + publisher=data['publisher'] + ) + response_data = {'message': 'Book created successfully', 'book_id': book.id} + return JsonResponse(response_data, status=201) + except IntegrityError: + response_data = {'message': 'Failed to create book, check input data'} + return JsonResponse(response_data, status=400) + + def delete(self, request, book_id=None): + if book_id: + book = get_object_or_404(Book, pk=book_id) + book.delete() + response_data = {'message': f'Book with id {book_id} deleted successfully'} + return JsonResponse(response_data, status=200) + else: + Book.objects.all().delete() + response_data = {'message': 'All books deleted successfully'} + return JsonResponse(response_data, status=200) + +class BookDetail(View): + def get(self, request, book_id=None): + book = get_object_or_404(Book, pk=book_id) + response_data = {"book": { + "title": book.title, + "author": book.author, + "release_date": book.release_date, + "publisher": book.publisher + }} + return JsonResponse(response_data) diff --git a/bookstore-django-py/bookstore_django_py/__init__.py b/bookstore-django-py/bookstore_django_py/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bookstore-django-py/bookstore_django_py/asgi.py b/bookstore-django-py/bookstore_django_py/asgi.py new file mode 100644 index 0000000..fdaac37 --- /dev/null +++ b/bookstore-django-py/bookstore_django_py/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for bookstore_django_py 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.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookstore_django_py.settings') + +application = get_asgi_application() diff --git a/bookstore-django-py/bookstore_django_py/settings.py b/bookstore-django-py/bookstore_django_py/settings.py new file mode 100644 index 0000000..166ef3c --- /dev/null +++ b/bookstore-django-py/bookstore_django_py/settings.py @@ -0,0 +1,128 @@ +""" +Django settings for bookstore_django_py project. + +Generated by 'django-admin startproject' using Django 4.2.1. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +import os +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.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-qywo6$m3(phau8$o!vvhog7vn8v@fkhcpc#w^9d_1cgc%2dchh' + +# 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', + 'books', +] + +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 = 'bookstore_django_py.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 = 'bookstore_django_py.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': os.getenv('DB_NAME'), + 'USER': os.getenv('DB_USER'), + 'PASSWORD': os.getenv('DB_PASSWORD'), + 'HOST': os.getenv('DB_HOST', '127.0.0.1'), + 'PORT': os.getenv('DB_PORT', '5432'), + } +} + +# Password validation +# https://docs.djangoproject.com/en/4.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/4.2/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.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/bookstore-django-py/bookstore_django_py/urls.py b/bookstore-django-py/bookstore_django_py/urls.py new file mode 100644 index 0000000..1695b70 --- /dev/null +++ b/bookstore-django-py/bookstore_django_py/urls.py @@ -0,0 +1,24 @@ +""" +URL configuration for bookstore_django_py project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.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 +from books.views import BookList, BookDetail + +urlpatterns = [ + path('books/', BookList.as_view()), + path('books//', BookDetail.as_view()), +] diff --git a/bookstore-django-py/bookstore_django_py/wsgi.py b/bookstore-django-py/bookstore_django_py/wsgi.py new file mode 100644 index 0000000..d9525f6 --- /dev/null +++ b/bookstore-django-py/bookstore_django_py/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for bookstore_django_py 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.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookstore_django_py.settings') + +application = get_wsgi_application() diff --git a/bookstore-django-py/manage.py b/bookstore-django-py/manage.py new file mode 100755 index 0000000..b46e91a --- /dev/null +++ b/bookstore-django-py/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', 'bookstore_django_py.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()