initiate drf app

This commit is contained in:
2025-05-15 18:26:23 +03:00
commit 8e3dfd89b1
86 changed files with 9340 additions and 0 deletions

15
backend/Pipfile Normal file
View File

@@ -0,0 +1,15 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
django = "*"
djangorestframework = "*"
python-dotenv = "*"
psycopg2 = "*"
[dev-packages]
[requires]
python_version = "3.12"

81
backend/Pipfile.lock generated Normal file
View File

@@ -0,0 +1,81 @@
{
"_meta": {
"hash": {
"sha256": "b373803326406c6ad8118054bb515b95be11d1fba2e9252d0914839e5c6ed309"
},
"pipfile-spec": 6,
"requires": {
"python_version": "3.12"
},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"asgiref": {
"hashes": [
"sha256:3e1e3ecc849832fe52ccf2cb6686b7a55f82bb1d6aee72a58826471390335e47",
"sha256:c343bd80a0bec947a9860adb4c432ffa7db769836c64238fc34bdc3fec84d590"
],
"markers": "python_version >= '3.8'",
"version": "==3.8.1"
},
"django": {
"hashes": [
"sha256:57fe1f1b59462caed092c80b3dd324fd92161b620d59a9ba9181c34746c97284",
"sha256:a9b680e84f9a0e71da83e399f1e922e1ab37b2173ced046b541c72e1589a5961"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==5.2.1"
},
"djangorestframework": {
"hashes": [
"sha256:bea7e9f6b96a8584c5224bfb2e4348dfb3f8b5e34edbecb98da258e892089361",
"sha256:f022ff46613584de994c0c6a4aebbace5fd700555fbe9d33b865ebf173eba6c9"
],
"index": "pypi",
"markers": "python_version >= '3.9'",
"version": "==3.16.0"
},
"psycopg2": {
"hashes": [
"sha256:0435034157049f6846e95103bd8f5a668788dd913a7c30162ca9503fdf542cb4",
"sha256:12ec0b40b0273f95296233e8750441339298e6a572f7039da5b260e3c8b60e11",
"sha256:47c4f9875125344f4c2b870e41b6aad585901318068acd01de93f3677a6522c2",
"sha256:4a579d6243da40a7b3182e0430493dbd55950c493d8c68f4eec0b302f6bbf20e",
"sha256:5df2b672140f95adb453af93a7d669d7a7bf0a56bcd26f1502329166f4a61716",
"sha256:65a63d7ab0e067e2cdb3cf266de39663203d38d6a8ed97f5ca0cb315c73fe067",
"sha256:88138c8dedcbfa96408023ea2b0c369eda40fe5d75002c0964c78f46f11fa442",
"sha256:91fd603a2155da8d0cfcdbf8ab24a2d54bca72795b90d2a3ed2b6da8d979dee2",
"sha256:9d5b3b94b79a844a986d029eee38998232451119ad653aea42bb9220a8c5066b",
"sha256:c6f7b8561225f9e711a9c47087388a97fdc948211c10a4bccbf0ba68ab7b3b5a"
],
"index": "pypi",
"markers": "python_version >= '3.8'",
"version": "==2.9.10"
},
"python-dotenv": {
"hashes": [
"sha256:41f90bc6f5f177fb41f53e87666db362025010eb28f60a01c9143bfa33a2b2d5",
"sha256:d7c01d9e2293916c18baf562d95698754b0dbbb5e74d457c45d4f6561fb9d55d"
],
"index": "pypi",
"markers": "python_version >= '3.9'",
"version": "==1.1.0"
},
"sqlparse": {
"hashes": [
"sha256:09f67787f56a0b16ecdbde1bfc7f5d9c3371ca683cfeaa8e6ff60b4807ec9272",
"sha256:cf2196ed3418f3ba5de6af7e82c694a9fbdbfecccdfc72e281548517081f16ca"
],
"markers": "python_version >= '3.8'",
"version": "==0.5.3"
}
},
"develop": {}
}

0
backend/api/__init__.py Normal file
View File

3
backend/api/admin.py Normal file
View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
backend/api/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'

View File

View File

@@ -0,0 +1,9 @@
from rest_framework import serializers
from mainpage.models import FAQ
class FAQMainSerializer(serializers.ModelSerializer):
class Meta:
model = FAQ
fields = "__all__"

19
backend/api/main/views.py Normal file
View File

@@ -0,0 +1,19 @@
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from api.utils.decorators import handle_exceptions
from api.main.serializers import FAQMainSerializer
from mainpage.models import FAQ
class FAQView(APIView):
@handle_exceptions
def get(self, request):
faqs = FAQ.objects.all()
data = {
'faqs': FAQMainSerializer(faqs, many=True).data
}
return Response(data, status=status.HTTP_200_OK)

View File

3
backend/api/models.py Normal file
View File

@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

3
backend/api/tests.py Normal file
View File

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

7
backend/api/urls.py Normal file
View File

@@ -0,0 +1,7 @@
from django.urls import path
from api.main.views import FAQView
urlpatterns = [
path("v1/faq/", FAQView.as_view(), name='faqMain'),
]

View File

@@ -0,0 +1,56 @@
from functools import wraps
from rest_framework.response import Response
from rest_framework import status
from django.core.exceptions import ValidationError, PermissionDenied
from django.http import Http404
from rest_framework.exceptions import APIException
def handle_exceptions(func):
"""
Обработчик ошибок для API endpoints
Обрабатывает различные типы исключений и возвращает соответствующие HTTP статусы
Текущие обрабоки:
- Ошибки валидации - HTTP400
- Объект не найден - HTTP404
- Ошибки доступа - HTTP403
- Обработки DRF исключений - вернется статус код от DRF
- Необработанные исключения - HTTP500
"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except ValidationError as e:
# ошибки валидации
return Response(
{"error": e.messages if hasattr(e, 'messages') else str(e)},
status=status.HTTP_400_BAD_REQUEST
)
except Http404 as e:
# объект не найден
return Response(
{"error": str(e) or "Запрашиваемый ресурс не найден"},
status=status.HTTP_404_NOT_FOUND
)
except PermissionDenied as e:
# ошибки доступа
return Response(
{"error": str(e) or "У вас нет прав для выполнения этого действия"},
status=status.HTTP_403_FORBIDDEN
)
except APIException as e:
# обработка DRF исключений
return Response(
{"error": str(e)},
status=e.status_code
)
except Exception as e:
# необработанные исключения
return Response(
{
"error": "Произошла внутренняя ошибка сервера",
"detail": str(e)
},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
return wrapper

0
backend/base/__init__.py Normal file
View File

16
backend/base/asgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
ASGI config for base 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/5.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings')
application = get_asgi_application()

114
backend/base/settings.py Normal file
View File

@@ -0,0 +1,114 @@
import os
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(dotenv_path=BASE_DIR / './.env')
SECRET_KEY = os.environ.get("SECRET_KEY")
DEBUG = os.environ.get("DEBUG_MODE")
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'routes.apps.RoutesConfig',
'mainpage.apps.MainpageConfig',
'rest_framework',
]
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 = 'base.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'base.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("DB_NAME"),
"USER": os.environ.get("DB_USER"),
"PASSWORD": os.environ.get("DB_PASSWORD"),
"HOST": os.environ.get("DB_HOST"),
"PORT": os.environ.get("DB_PORT"),
}
}
# Password validation
# https://docs.djangoproject.com/en/5.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/5.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/5.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

23
backend/base/urls.py Normal file
View File

@@ -0,0 +1,23 @@
"""
URL configuration for base project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.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('api/', include('api.urls')),
]

16
backend/base/wsgi.py Normal file
View File

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

View File

View File

@@ -0,0 +1,4 @@
from django.contrib import admin
from .models import FAQ
admin.site.register(FAQ)

6
backend/mainpage/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class MainpageConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'mainpage'

View File

@@ -0,0 +1,26 @@
# Generated by Django 5.2.1 on 2025-05-15 14:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FAQ',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=250)),
('content', models.CharField(max_length=800)),
],
options={
'verbose_name': 'FAQ',
'verbose_name_plural': 'FAQs',
},
),
]

View File

View File

@@ -0,0 +1,14 @@
from django.db import models
class FAQ (models.Model):
title = models.CharField(max_length=250)
content = models.CharField(max_length=800)
class Meta:
verbose_name = 'FAQ'
verbose_name_plural = 'FAQs'
ordering = ['id']
def __str__(self):
return self.title

View File

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

22
backend/manage.py Executable file
View File

@@ -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', 'base.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()

View File

3
backend/routes/admin.py Normal file
View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
backend/routes/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class RoutesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'routes'

View File

@@ -0,0 +1,24 @@
type_transport_choices = [
("road", "Авто"),
("avia", "Авиа"),
('both', "Любой"),
]
transfer_location_choices = [
("airport", "В аэропорту"),
("city", "По городу"),
("other", "По договоренности")
]
cargo_type_choices = [
("letter", "Письмо или Документы"),
("package", "Посылка (до 30кг)"),
("passenger", "Попутчик"),
("parcel", "Бандероль (до 5кг)"),
("cargo", "Груз (свыше 30 кг)"),
]
owner_type_choices = [
("customer", "Заказчик"),
("mover", "Перевозчик")
]

View File

3
backend/routes/models.py Normal file
View File

@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

3
backend/routes/tests.py Normal file
View File

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

3
backend/routes/views.py Normal file
View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.