Skip to content

Commit

Permalink
Merge branch 'main' into feature/comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Reagent992 authored Jan 23, 2024
2 parents b7c4fd5 + 1efaf47 commit a716051
Show file tree
Hide file tree
Showing 31 changed files with 1,035 additions and 64 deletions.
9 changes: 9 additions & 0 deletions .envexample
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,12 @@ SECRET_KEY=django-insecure-pp6rzgeb5sjtbhfs(d-3*ibq67#0c-8jsd82@65!+=$satw167
DEBUG=False
TIME_ZONE=Europe/Moscow
LANGUAGE_CODE=ru-RU

USE_POSTGRESQL=False
DB_NAME=IPR
DB_HOST=db
DB_PORT=5432
USE_POSTGRESQL=True
POSTGRES_DB=ipr
POSTGRES_USER=ipr_user
POSTGRES_PASSWORD=ipr_password
33 changes: 33 additions & 0 deletions .github/workflows/code-style.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Code-style workflow

on: [push]

jobs:
tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.12",]

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r ./requirements.txt
- name: Run Black formatter
run: black --check --diff --config ./pyproject.toml .

- name: Run isort
run: isort --check --diff --settings-file ./pyproject.toml .

- name: Run flake8
run: flake8 --verbose --config ./setup.cfg .
8 changes: 6 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -149,5 +149,9 @@ dmypy.json
.DS_Store
Thumbs.db

/backend/media/
/backend/collected_static/
/media/
/collected_static/
.vscode
*/migrations/*
/static/
# Миграции убраны из git. Т.к. до существования БД проще без них.
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ repos:
types: [ python ]
pass_filenames: false
args: ["--verbose"]

- id: django-test
name: django-test
entry: python manage.py test
language: system
types: [ python ]
pass_filenames: false
62 changes: 42 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,48 @@
# Backend Проекта "ИПР". Хакатон Яндекс-Альфа-Банк. Команда №8.
# Backend Проекта "ИПР". Хакатон Яндекс-Альфа-Банк. Команда №8

# Backend
Тут описаны технические моменты backend.
![GitHub Actions](https://github.com/Reagent992/ipr-hackathon-yandex-alfa/blob/main/.github/workflows/code-style.yml/badge.svg)\
![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)
![DjangoREST](https://img.shields.io/badge/DJANGO-REST-ff1709?style=for-the-badge&logo=django&logoColor=white&color=ff1709&labelColor=gray)
![Docker](https://img.shields.io/badge/docker-%230db7ed.svg?style=for-the-badge&logo=docker&logoColor=white)
![Nginx](https://img.shields.io/badge/nginx-%23009639.svg?style=for-the-badge&logo=nginx&logoColor=white)

TO-DO: Описание проекта.

## [Репозиторий Frontend](https://github.com/NataliyaNikulshina/ipr-hackathon-yandex-alfa)

## Документация

Пример адреса на запущенном сервере:
- http://127.0.0.1:8000/api/v1/swagger/
- http://127.0.0.1:8000/api/v1/redoc/

## Используемые библиотеки и т.д.:
- Python 3.12
- Django: Основной фреймворк.
- DRF: API.
- Gunicorn: WSGI-сервер
- Environs: Хранение секретов.
- Drf-yasg: Генератор документации; swagger-генератор.
- Djoser: Для аутентификации.
- Django_filters: Для легкой фильтрации данных.
- Flake8, black, isort, Pre-commit: Для Code-Style.

- <http://127.0.0.1:8000/api/v1/swagger/>
- <http://127.0.0.1:8000/api/v1/redoc/>

## Используемые библиотеки и зависимости

| Библиотека | Описание |
|-|-|
| [Python 3.12](https://www.python.org/) | Язык программирования Python версии 3.12.|
| [Django](https://pypi.org/project/Django/)| Основной фреймворк для разработки веб-приложений. |
| [DRF](https://pypi.org/project/djangorestframework/)| Фреймворк для создания API в приложениях Django.|
| [Gunicorn](https://pypi.org/project/gunicorn/)| WSGI-сервер для запуска веб-приложений Django. |
| [Environs](https://pypi.org/project/environs/) | Библиотека для управления переменными окружения и хранения секретов. |
| [drf-spectacular](https://drf-spectacular.readthedocs.io/en/latest/index.html) | Генератор документации и Swagger для API в Django. |
| [Djoser](https://pypi.org/project/djoser/) | Библиотека для обеспечения аутентификации в приложениях Django. |
| [Pillow](https://pypi.org/project/pillow/) | Библиотека для обработки изображений в Python. |
| [Django filter](https://pypi.org/project/django-filter/) | Библиотека для легкой фильтрации данных в приложениях Django. |
| [Flake8](https://pypi.org/project/flake8/), [black](https://pypi.org/project/black/), [isort](https://pypi.org/project/isort/), [Pre-commit](https://pypi.org/project/pre-commit/) | Инструменты для поддержания Code-Style в проекте. |

## Code-Style
- Flake8
- black
- isort
- Pre-commit

### Локальный запуск pre-commit

- В начале требует активации хуков `pre-commit install`
- Далее будет запускаться при попытке сделать commit или при запуске `pre-commit`

## Запуск проекта

### 1. Требуется заполнить `.env` файл, пример заполнения находится в `.envexample`

## Авторы

TO-DO
File renamed without changes.
23 changes: 23 additions & 0 deletions api/v1/serializers/api/users_serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from djoser.serializers import UserSerializer

from users.models import User


class CustomUserSerializer(UserSerializer):
"""Сериализатор пользователей."""

class Meta:
model = User
fields = (
"id",
"email",
"username",
"first_name",
"last_name",
"patronymic",
"position",
"is_boss",
"date_joined",
"last_login",
"userpic",
)
15 changes: 15 additions & 0 deletions api/v1/serializers/task.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.relations import SlugRelatedField

from tasks.models import Task

User = get_user_model()


class TaskSerializer(serializers.ModelSerializer):
creator = SlugRelatedField(slug_field="username", read_only=True)

class Meta:
exclude = ("creation_date",)
model = Task
41 changes: 19 additions & 22 deletions api/v1/urls.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,34 @@
from django.urls import include, path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions, routers
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularRedocView,
SpectacularSwaggerView,
)
from rest_framework import routers

from api.v1.views.task import TaskViewSet
from api.v1.views.users_view import UserViewSet

v1_router = routers.DefaultRouter()
v1_router.register("tasks", TaskViewSet, basename="tasks")
v1_router.register("users", UserViewSet)

urlpatterns = [
path("", include(v1_router.urls)),
path("auth/", include("djoser.urls")),
path("auth/", include("djoser.urls.jwt")),
]

# ----------------------------------------------------------------------SWAGGER
schema_view = get_schema_view(
openapi.Info(
title="IPR API",
default_version="v1",
description="Документация для приложения ИПР.",
license=openapi.License(name="MIT License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)

# ---------------------------------------------------------------------SWAGGER
urlpatterns += [
path("schema/", SpectacularAPIView.as_view(), name="schema"),
path(
"swagger/",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
"schema/swagger-ui/",
SpectacularSwaggerView.as_view(url_name="schema"),
name="swagger-ui",
),
path(
"redoc/",
schema_view.with_ui("redoc", cache_timeout=0),
name="schema-redoc",
"schema/redoc/",
SpectacularRedocView.as_view(url_name="schema"),
name="redoc",
),
]
Empty file added api/v1/views/__init__.py
Empty file.
12 changes: 12 additions & 0 deletions api/v1/views/task.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from rest_framework import viewsets

from api.v1.serializers.task import TaskSerializer
from tasks.models import Task


class TaskViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all()
serializer_class = TaskSerializer

def perform_create(self, serializer):
serializer.save(creator_id=self.request.user.id)
16 changes: 16 additions & 0 deletions api/v1/views/users_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from djoser.views import UserViewSet as UserViewSetFromDjoser
from drf_spectacular.utils import extend_schema
from rest_framework.pagination import PageNumberPagination

from api.v1.serializers.api.users_serializer import CustomUserSerializer


@extend_schema(
responses=CustomUserSerializer,
description="Пользователи.",
)
class UserViewSet(UserViewSetFromDjoser):
"""Пользователи."""

serializer_class = CustomUserSerializer
pagination_class = PageNumberPagination
Loading

0 comments on commit a716051

Please sign in to comment.