First sprint

This commit is contained in:
Francesco Esposito 2019-11-23 01:36:02 +01:00
parent a090ac0bde
commit 4b71e61ff7
22 changed files with 551 additions and 0 deletions

21
manage.py Executable file
View File

@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'segnalibre.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()

0
segnalibre/__init__.py Normal file
View File

135
segnalibre/settings.py Normal file
View File

@ -0,0 +1,135 @@
"""
Django settings for segnalibre project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret' # os environment
# 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',
'corsheaders',
'django_filters',
'segnalibre_app'
]
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 = 'segnalibre.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 = 'segnalibre.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Rome'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
CORS_ORIGIN_WHITELIST = [
"http://localhost:8000",
"http://127.0.0.1:3000"
]
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

24
segnalibre/urls.py Normal file
View File

@ -0,0 +1,24 @@
"""segnalibre URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('segnalibre_app.urls'))
]

16
segnalibre/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for segnalibre 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/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'segnalibre.settings')
application = get_wsgi_application()

View File

6
segnalibre_app/admin.py Normal file
View File

@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Book, Bookmark
# Register your models here.
admin.site.register(Book)
admin.site.register(Bookmark)

5
segnalibre_app/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class SegnalibreAppConfig(AppConfig):
name = 'segnalibre_app'

View File

@ -0,0 +1,40 @@
# Generated by Django 2.2.7 on 2019-11-22 20:55
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('author', models.CharField(max_length=100)),
('publisher', models.CharField(max_length=100)),
('pub_date', models.DateField()),
('pages', models.IntegerField()),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('create_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Bookmark',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('position', models.IntegerField()),
('created', models.DateTimeField(auto_now_add=True)),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='segnalibre_app.Book')),
],
),
]

View File

@ -0,0 +1,17 @@
# Generated by Django 2.2.7 on 2019-11-22 21:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('segnalibre_app', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='book',
name='create_by',
),
]

View File

@ -0,0 +1,26 @@
# Generated by Django 2.2.7 on 2019-11-22 21:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('segnalibre_app', '0002_remove_book_create_by'),
]
operations = [
migrations.AddField(
model_name='book',
name='owner',
field=models.ForeignKey(default=-1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='bookmark',
name='owner',
field=models.ForeignKey(default=-1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]

View File

@ -0,0 +1,25 @@
# Generated by Django 2.2.7 on 2019-11-22 21:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('segnalibre_app', '0003_auto_20191122_2202'),
]
operations = [
migrations.AlterField(
model_name='book',
name='owner',
field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='bookmark',
name='owner',
field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]

View File

@ -0,0 +1,25 @@
# Generated by Django 2.2.7 on 2019-11-22 21:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('segnalibre_app', '0004_auto_20191122_2226'),
]
operations = [
migrations.AlterField(
model_name='book',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='bookmark',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]

View File

@ -0,0 +1,25 @@
# Generated by Django 2.2.7 on 2019-11-22 21:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('segnalibre_app', '0005_auto_20191122_2228'),
]
operations = [
migrations.AlterField(
model_name='book',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='books', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='bookmark',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bookmarks', to=settings.AUTH_USER_MODEL),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 2.2.7 on 2019-11-22 22:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('segnalibre_app', '0006_auto_20191122_2231'),
]
operations = [
migrations.AddField(
model_name='book',
name='position',
field=models.IntegerField(default=0),
),
]

View File

25
segnalibre_app/models.py Normal file
View File

@ -0,0 +1,25 @@
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publisher = models.CharField(max_length=100)
pub_date = models.DateField()
pages = models.IntegerField()
position = models.IntegerField(default=0)
owner = models.ForeignKey('auth.User', related_name='books', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def _str_(self):
return self.title
class Bookmark(models.Model):
position = models.IntegerField()
book = models.ForeignKey(Book, on_delete=models.CASCADE)
owner = models.ForeignKey('auth.User', related_name='bookmarks', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
def _str_(self):
return self.title

View File

@ -0,0 +1,11 @@
from rest_framework import permissions
class isOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user

View File

@ -0,0 +1,39 @@
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Book, Bookmark
class BookSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Book
fields = (
'id',
'title',
'author',
'publisher',
'pub_date',
'pages',
'position',
'owner',
'created',
'updated'
)
class UserSerializer(serializers.ModelSerializer):
books = serializers.PrimaryKeyRelatedField(many=True, queryset=Book.objects.all())
class Meta:
model = User
fields = ['id', 'username', 'books']
class BookmarkSerilizer(serializers.ModelSerializer):
class Meta:
model = Bookmark
fields = (
'id',
'position',
'book',
'owner',
'created'
)

3
segnalibre_app/tests.py Normal file
View File

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

10
segnalibre_app/urls.py Normal file
View File

@ -0,0 +1,10 @@
from django.urls import path, include
from . import views
urlpatterns = [
path('users/', views.UserList.as_view()),
path('users/<int:pk>/', views.UserDetail.as_view()),
path('books/', views.BookList.as_view()),
path('books/<int:pk>/', views.BookDetail.as_view()),
path('api-auth/', include('rest_framework.urls'))
]

80
segnalibre_app/views.py Normal file
View File

@ -0,0 +1,80 @@
import django_filters.rest_framework
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework import viewsets, filters, generics, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.http import Http404
from django_filters.rest_framework import DjangoFilterBackend
from .serializers import BookSerializer, BookmarkSerilizer, UserSerializer
from .models import Book, Bookmark
from .permissions import isOwner
# Create your views here.
class UserList(APIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class BookList(APIView):
serializer_class = BookSerializer
#queryset = Book.objects.all()
#filter_backends = [filters.SearchFilter, filters.OrderingFilter]
#search_fields = ['title', 'author']
#ordering_fields = ['pub_date', 'title', 'author']
#ordering = ['title']
permission_classes = [permissions.IsAuthenticated, isOwner]
def get(self, request, format=None):
books = Book.objects.filter(owner=request.user)
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save(owner=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BookDetail(APIView):
#serializer_class = BookSerializer
#queryset = Book.objects.all()
#filter_backends = [filters.SearchFilter, filters.OrderingFilter]
#search_fields = ['title', 'author']
#ordering_fields = ['pub_date', 'title', 'author']
#ordering = ['title']
permission_classes = [permissions.IsAuthenticated, isOwner]
def get_object(self, pk, owner=None):
try:
return Book.objects.get(pk=pk, owner=owner)
except Book.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
book = self.get_object(pk, request.user)
serializer = BookSerializer(book)
return Response(serializer.data)
def put(self, request, pk, format=None):
book = self.get_object(pk, request.user)
serializer = BookSerializer(book, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
book = self.get_object(pk, request.user)
book.delete()
return Response(status=status.HTTP_204_NO_CONTENT)