lab-2: add Caddy-based configuration as extra task

This commit is contained in:
DeevEV 2026-05-28 12:16:14 +03:00
parent 4ad876fe5a
commit 3d177a55bb
24 changed files with 416 additions and 31 deletions

View file

@ -0,0 +1,4 @@
.env
certs/
__pycache__/
*.pyc

24
lab-2/caddy/Caddyfile Normal file
View file

@ -0,0 +1,24 @@
{
auto_https off
}
:80 {
redir https://{host}{uri} permanent
}
:443 {
tls /run/secrets/lab2_crt /run/secrets/lab2_key
handle_path /static/* {
root * /staticfiles
file_server
}
handle /admin/* {
reverse_proxy backend_service:8000
}
handle /api/* {
reverse_proxy backend_service:8000
}
}

View file

@ -0,0 +1,11 @@
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

View file

View file

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

View file

@ -0,0 +1,133 @@
"""
Django settings for lab1 project.
Generated by 'django-admin startproject' using Django 6.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.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/6.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--xqwhdo2$)n*y3yk=d*vmwx6nuwt8h=m5@_og_uzj+11^hu7))'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
CSRF_TRUSTED_ORIGINS = ['http://localhost', 'https://localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'quiz',
]
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 = 'lab1.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 = 'lab1.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('POSTGRES_DB', 'lab_db'),
'USER': os.environ.get('POSTGRES_USER', 'django'),
'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'password'),
'HOST': os.environ.get('POSTGRES_HOST', 'postgres_service'),
'PORT': os.environ.get('POSTGRES_PORT', 5432),
}
}
# Password validation
# https://docs.djangoproject.com/en/6.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/6.0/topics/i18n/
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
# Default primary key field type
# https://docs.djangoproject.com/en/6.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View file

@ -0,0 +1,13 @@
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from quiz.views import QuizViewSet
router = routers.DefaultRouter()
router.register(r'quiz', QuizViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
]

View file

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

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', 'lab1.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

View file

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

View file

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

View file

@ -0,0 +1,18 @@
import random
from .models import Quiz
from django.db import transaction
from faker import Faker
fk = Faker()
def gentestdata():
with transaction.atomic():
for i in range(100):
new_quiz = Quiz()
new_quiz.title = fk.sentence(nb_words=4)
new_quiz.description = fk.paragraph()
new_quiz.author = fk.name()
new_quiz.time_limit = random.randint(5, 60)
new_quiz.is_published = random.random() > 0.5
new_quiz.save()
print('Сделана генерация')

View file

@ -0,0 +1,26 @@
# Generated by Django 6.0.3 on 2026-03-05 08:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Quiz',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('description', models.TextField()),
('author', models.CharField(max_length=100)),
('created_at', models.DateTimeField(auto_now_add=True)),
('time_limit', models.IntegerField(help_text='Ограничение по времени в минутах')),
('is_published', models.BooleanField(default=False)),
],
),
]

View file

@ -0,0 +1,15 @@
from django.db import models
# Create your models here.
class Quiz(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
author = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
time_limit = models.IntegerField(help_text='Ограничение по времени в минутах')
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title

View file

@ -0,0 +1,7 @@
from rest_framework import serializers
from .models import Quiz
class QuizSerializer(serializers.ModelSerializer):
class Meta:
model = Quiz
fields = '__all__'

View file

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

View file

@ -0,0 +1,9 @@
from django.shortcuts import render
from rest_framework import viewsets
from .models import Quiz
from .serializers import QuizSerializer
class QuizViewSet(viewsets.ModelViewSet):
queryset = Quiz.objects.all()
serializer_class = QuizSerializer

View file

@ -0,0 +1,8 @@
Django
djangorestframework
markdown
django-filter
django-cors-headers
psycopg[binary,pool]
faker
gunicorn

View file

@ -0,0 +1,55 @@
name: lab2-caddy
secrets:
lab2_crt:
file: ./certs/lab2.crt
lab2_key:
file: ./certs/lab2.key
services:
postgres_service:
image: postgres:16-alpine
env_file:
- .env
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 30s
retries: 5
volumes:
- postgres_data:/var/lib/postgresql/data
backend_service:
build: ./backend
command: >
sh -c "python manage.py migrate &&
python manage.py shell -c 'from quiz.gentestdata import gentestdata; gentestdata()' &&
python manage.py collectstatic --no-input &&
gunicorn lab1.wsgi:application --bind 0.0.0.0:8000"
volumes:
- static_volume:/app/staticfiles
env_file:
- .env
depends_on:
postgres_service:
condition: service_healthy
restart: unless-stopped
caddy_service:
image: caddy:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- static_volume:/staticfiles:ro
secrets:
- lab2_crt
- lab2_key
depends_on:
- backend_service
restart: unless-stopped
volumes:
static_volume:
postgres_data:

26
lab-2/caddy/gen-cert.sh Normal file
View file

@ -0,0 +1,26 @@
#!/bin/sh
set -e
mkdir -p certs
# 1. Генерация корневого сертификата root.crt и его rsa-ключа root.key
openssl req -x509 -new -nodes -newkey rsa:2048 \
-keyout certs/root.key -days 3650 \
-out certs/root.crt -subj "//CN=Root CA"
# 2. Генерация rsa-ключа для сертификата сервера и вспомогательного CSR-файла (Certificate Signing Request) на основе этого ключа
openssl req -new -nodes -newkey rsa:2048 \
-keyout certs/lab2.key -out certs/lab2.csr \
-subj "//CN=lab2 server cert"
# 3. Собственно, генерация сертификата сервера *.crt из *.csr-файла, сгенерированного выше
echo "subjectAltName=DNS:localhost,IP:127.0.0.1" > certs/extfile.txt
openssl x509 -req -in certs/lab2.csr -days 3650 \
-CA certs/root.crt -CAkey certs/root.key \
-CAcreateserial -out certs/lab2.crt \
-sha256 -extfile certs/extfile.txt
rm certs/extfile.txt
# 4. Удаление вспомогательного CSR-файла
rm certs/lab2.csr
echo "Done. Certificates written to ./certs/"

File diff suppressed because one or more lines are too long

View file

@ -1,33 +1,3 @@
/*
* api_client.h HTTP-клиент, реализующий паттерн «Синглтон»
*
*
* ПАТТЕРН «СИНГЛТОН» (Singleton)
*
* Задача: гарантировать, что в приложении существует ровно
* ОДИН экземпляр QNetworkAccessManager. Создание нескольких
* менеджеров приводит к дублированию соединений и cookie-хранилищ.
*
* Реализация (Meyers' Singleton):
* статическая локальная переменная в instance()
* конструктор объявлен private
* копирующий конструктор и operator= удалены (= delete)
*
*
* ApiClient также является «клиентом» паттерна «Адаптер»:
* он хранит указатель на IQuizAdapter и использует его
* для преобразования ответов сервера в Quiz-объекты,
* не зная о деталях реализации парсинга.
*
* Коммуникация с вызывающим кодом через механизм сигналов Qt:
* quizzesReceived список тестов успешно получен и десериализован
* quizReceived один тест успешно получен и десериализован
* quizCreated тест создан (POST)
* quizUpdated тест обновлён (PUT)
* quizDeleted тест удалён (DELETE)
* errorOccurred произошла сетевая ошибка или ошибка парсинга
*/
#pragma once #pragma once
#include <QObject> #include <QObject>