diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/__pycache__/__init__.cpython-313.pyc b/api/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..aa92400 Binary files /dev/null and b/api/__pycache__/__init__.cpython-313.pyc differ diff --git a/api/__pycache__/admin.cpython-313.pyc b/api/__pycache__/admin.cpython-313.pyc new file mode 100644 index 0000000..a19afdd Binary files /dev/null and b/api/__pycache__/admin.cpython-313.pyc differ diff --git a/api/__pycache__/apps.cpython-313.pyc b/api/__pycache__/apps.cpython-313.pyc new file mode 100644 index 0000000..07bd8ee Binary files /dev/null and b/api/__pycache__/apps.cpython-313.pyc differ diff --git a/api/__pycache__/models.cpython-313.pyc b/api/__pycache__/models.cpython-313.pyc new file mode 100644 index 0000000..1468336 Binary files /dev/null and b/api/__pycache__/models.cpython-313.pyc differ diff --git a/api/__pycache__/serializer.cpython-313.pyc b/api/__pycache__/serializer.cpython-313.pyc new file mode 100644 index 0000000..269daf2 Binary files /dev/null and b/api/__pycache__/serializer.cpython-313.pyc differ diff --git a/api/__pycache__/serializers.cpython-313.pyc b/api/__pycache__/serializers.cpython-313.pyc new file mode 100644 index 0000000..70e2ce5 Binary files /dev/null and b/api/__pycache__/serializers.cpython-313.pyc differ diff --git a/api/__pycache__/tests.cpython-313.pyc b/api/__pycache__/tests.cpython-313.pyc new file mode 100644 index 0000000..888b4ba Binary files /dev/null and b/api/__pycache__/tests.cpython-313.pyc differ diff --git a/api/__pycache__/urls.cpython-313.pyc b/api/__pycache__/urls.cpython-313.pyc new file mode 100644 index 0000000..39809bb Binary files /dev/null and b/api/__pycache__/urls.cpython-313.pyc differ diff --git a/api/__pycache__/views.cpython-313.pyc b/api/__pycache__/views.cpython-313.pyc new file mode 100644 index 0000000..8c1e868 Binary files /dev/null and b/api/__pycache__/views.cpython-313.pyc differ diff --git a/api/admin.py b/api/admin.py new file mode 100644 index 0000000..c47772a --- /dev/null +++ b/api/admin.py @@ -0,0 +1,7 @@ +from django.contrib import admin + +from .models import User, Prediction, UserPrediction + +admin.site.register(User) +admin.site.register(Prediction) +admin.site.register(UserPrediction) \ No newline at end of file diff --git a/api/apps.py b/api/apps.py new file mode 100644 index 0000000..66656fd --- /dev/null +++ b/api/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ApiConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'api' diff --git a/api/build_qstring.py b/api/build_qstring.py new file mode 100644 index 0000000..f724f6c --- /dev/null +++ b/api/build_qstring.py @@ -0,0 +1,38 @@ +import urllib.parse + +def build_query_string(data: dict) -> str: + required_keys = [ + "profile", + "pred_type", + "launch_datetime", + "launch_latitude", + "launch_longitude", + "launch_altitude", + "ascent_rate", + "burst_altitude", + "descent_rate" + ] + + # Проверяем, что все ключи на месте + missing_keys = [key for key in required_keys if key not in data] + if missing_keys: + raise ValueError(f"Missing required keys: {', '.join(missing_keys)}") + + # Собираем строку запроса + return urllib.parse.urlencode({k: data[k] for k in required_keys}) + +# Пример: +json_data = { + "profile": "standard_profile", + "pred_type": "single", + "launch_datetime": "2025-03-16T08:47:00Z", + "launch_latitude": "56.6992", + "launch_longitude": "38.8247", + "launch_altitude": "0", + "ascent_rate": "5", + "burst_altitude": "30000", + "descent_rate": "5" +} + +query_string = build_query_string(json_data) +print(query_string) \ No newline at end of file diff --git a/api/migrations/0001_initial.py b/api/migrations/0001_initial.py new file mode 100644 index 0000000..ee34459 --- /dev/null +++ b/api/migrations/0001_initial.py @@ -0,0 +1,22 @@ +# Generated by Django 5.1.7 on 2025-03-15 08:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Todo', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=100)), + ('completed', models.BooleanField(default=False)), + ], + ), + ] diff --git a/api/migrations/0002_prediction_user_userprediction_delete_todo.py b/api/migrations/0002_prediction_user_userprediction_delete_todo.py new file mode 100644 index 0000000..e62cc82 --- /dev/null +++ b/api/migrations/0002_prediction_user_userprediction_delete_todo.py @@ -0,0 +1,46 @@ +# Generated by Django 5.1.7 on 2025-03-31 10:14 + +import django.db.models.deletion +import uuid +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Prediction', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('result', models.JSONField()), + ('deleted_at', models.DateTimeField(blank=True, null=True)), + ], + ), + migrations.CreateModel( + name='User', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ], + ), + migrations.CreateModel( + name='UserPrediction', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('prediction', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.prediction')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.user')), + ], + options={ + 'unique_together': {('user', 'prediction')}, + }, + ), + migrations.DeleteModel( + name='Todo', + ), + ] diff --git a/api/migrations/__init__.py b/api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/migrations/__pycache__/0001_initial.cpython-313.pyc b/api/migrations/__pycache__/0001_initial.cpython-313.pyc new file mode 100644 index 0000000..0939751 Binary files /dev/null and b/api/migrations/__pycache__/0001_initial.cpython-313.pyc differ diff --git a/api/migrations/__pycache__/0002_prediction_user_userprediction_delete_todo.cpython-313.pyc b/api/migrations/__pycache__/0002_prediction_user_userprediction_delete_todo.cpython-313.pyc new file mode 100644 index 0000000..cff1936 Binary files /dev/null and b/api/migrations/__pycache__/0002_prediction_user_userprediction_delete_todo.cpython-313.pyc differ diff --git a/api/migrations/__pycache__/__init__.cpython-313.pyc b/api/migrations/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..620db1b Binary files /dev/null and b/api/migrations/__pycache__/__init__.cpython-313.pyc differ diff --git a/api/models.py b/api/models.py new file mode 100644 index 0000000..a66861d --- /dev/null +++ b/api/models.py @@ -0,0 +1,20 @@ +import uuid +from django.db import models + +class User(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + +class Prediction(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + result = models.JSONField() + deleted_at = models.DateTimeField(null=True, blank=True) + +class UserPrediction(models.Model): + user = models.ForeignKey(User, on_delete=models.CASCADE) + prediction = models.ForeignKey(Prediction, on_delete=models.CASCADE) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + unique_together = ('user', 'prediction') diff --git a/api/serializers.py b/api/serializers.py new file mode 100644 index 0000000..3f0dc4f --- /dev/null +++ b/api/serializers.py @@ -0,0 +1,7 @@ +from rest_framework import serializers +from .models import Prediction + +class PredictionSerializer(serializers.ModelSerializer): + class Meta: + model = Prediction + fields = ['id', 'created_at', 'updated_at', 'result'] diff --git a/api/tests.py b/api/tests.py new file mode 100644 index 0000000..bbe8b3e --- /dev/null +++ b/api/tests.py @@ -0,0 +1,10 @@ +from django.test import TestCase +from rest_framework.test import APIClient +from .models import User + +class PredictionTest(TestCase): + def setUp(self): + self.client = APIClient() + self.user = User.objects.create() + + diff --git a/api/urls.py b/api/urls.py new file mode 100644 index 0000000..248713c --- /dev/null +++ b/api/urls.py @@ -0,0 +1,10 @@ +from django.urls import path +from .views import PredictionCreateView, PredictionListView, PredictionDeleteView +from rest_framework.authtoken.views import obtain_auth_token + +urlpatterns = [ + path('predictions', PredictionCreateView.as_view(), name='create_prediction'), + path('predictions', PredictionListView.as_view(), name='get_predictions'), + path('predictions/', PredictionDeleteView.as_view(), name='delete_prediction'), + path('api/token/', obtain_auth_token), +] diff --git a/api/views.py b/api/views.py new file mode 100644 index 0000000..803abe6 --- /dev/null +++ b/api/views.py @@ -0,0 +1,63 @@ +from rest_framework import status, generics +from rest_framework.response import Response +from rest_framework.views import APIView +from django.utils import timezone +from .models import Prediction, User, UserPrediction +from .serializers import PredictionSerializer +from rest_framework.permissions import IsAuthenticated +import requests + +def get_prediction_from_tawhiri(params): + base_url = "https://fly.stratonautica.ru/api/v2" + response = requests.get(base_url, params=params) + + if response.status_code == 200: + return response.json() # получаем результат предсказания + else: + raise Exception(f"Tawhiri error: {response.status_code} {response.text}") + + +class PredictionCreateView(APIView): + def post(self, request): + user_id = request.data.get('user_id') + user = User.objects.get(id=user_id) + + # Передаём остальные параметры (кроме user_id) в Tawhiri + tawhiri_params = {k: v for k, v in request.data.items() if k != 'user_id'} + + try: + prediction_result = get_prediction_from_tawhiri(tawhiri_params) + except Exception as e: + return Response({"error": str(e)}, status=500) + + prediction = Prediction.objects.create(result=prediction_result) + UserPrediction.objects.create(user=user, prediction=prediction) + + return Response(PredictionSerializer(prediction).data) + +class PredictionListView(APIView): + def get(self, request): + user_id = request.query_params.get('user_id') + created_from = request.query_params.get('created_from') + created_till = request.query_params.get('created_till') + + predictions = Prediction.objects.filter( + id__in=UserPrediction.objects.filter(user_id=user_id).values_list('prediction_id'), + created_at__gte=created_from, + created_at__lte=created_till, + deleted_at__isnull=True + ) + return Response(PredictionSerializer(predictions, many=True).data) + +class PredictionDeleteView(APIView): + def delete(self, request, pk): + try: + prediction = Prediction.objects.get(pk=pk) + prediction.deleted_at = timezone.now() + prediction.save() + return Response({"deleted": True}) + except Prediction.DoesNotExist: + return Response({"error": "Not found"}, status=404) + +class PredictionCreateView(APIView): + permission_classes = [IsAuthenticated] \ No newline at end of file diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000..5be43ec Binary files /dev/null and b/db.sqlite3 differ diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..008da0d --- /dev/null +++ b/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', 'testapi.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() diff --git a/testapi/__init__.py b/testapi/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/testapi/__pycache__/__init__.cpython-313.pyc b/testapi/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..c282104 Binary files /dev/null and b/testapi/__pycache__/__init__.cpython-313.pyc differ diff --git a/testapi/__pycache__/models.cpython-313.pyc b/testapi/__pycache__/models.cpython-313.pyc new file mode 100644 index 0000000..83bc908 Binary files /dev/null and b/testapi/__pycache__/models.cpython-313.pyc differ diff --git a/testapi/__pycache__/serializer.cpython-313.pyc b/testapi/__pycache__/serializer.cpython-313.pyc new file mode 100644 index 0000000..adac9f7 Binary files /dev/null and b/testapi/__pycache__/serializer.cpython-313.pyc differ diff --git a/testapi/__pycache__/settings.cpython-313.pyc b/testapi/__pycache__/settings.cpython-313.pyc new file mode 100644 index 0000000..6f91e0b Binary files /dev/null and b/testapi/__pycache__/settings.cpython-313.pyc differ diff --git a/testapi/__pycache__/urls.cpython-313.pyc b/testapi/__pycache__/urls.cpython-313.pyc new file mode 100644 index 0000000..6930a4d Binary files /dev/null and b/testapi/__pycache__/urls.cpython-313.pyc differ diff --git a/testapi/__pycache__/views.cpython-313.pyc b/testapi/__pycache__/views.cpython-313.pyc new file mode 100644 index 0000000..ee722e2 Binary files /dev/null and b/testapi/__pycache__/views.cpython-313.pyc differ diff --git a/testapi/__pycache__/wsgi.cpython-313.pyc b/testapi/__pycache__/wsgi.cpython-313.pyc new file mode 100644 index 0000000..2be936e Binary files /dev/null and b/testapi/__pycache__/wsgi.cpython-313.pyc differ diff --git a/testapi/asgi.py b/testapi/asgi.py new file mode 100644 index 0000000..b3f8740 --- /dev/null +++ b/testapi/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for testapi 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.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapi.settings') + +application = get_asgi_application() diff --git a/testapi/settings.py b/testapi/settings.py new file mode 100644 index 0000000..641c282 --- /dev/null +++ b/testapi/settings.py @@ -0,0 +1,142 @@ +""" +Django settings for testapi project. + +Generated by 'django-admin startproject' using Django 5.1.7. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.1/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/5.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-np(nxnh6mw)v4pa2n2z3pl_5&!2z$jshhak9r3v=y1u9rd*sl!' + +# 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', + 'rest_framework.authtoken', + 'drf_spectacular', + 'api' +] + +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 = 'testapi.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 = 'testapi.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': 'drfapi', # Your database name + 'USER': 'postgres', # Your PostgreSQL username + 'PASSWORD': '1235', # Your PostgreSQL password + 'HOST': 'localhost', # Or your DB server's IP + 'PORT': '5432', # Default PostgreSQL port + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.1/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.1/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.1/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +REST_FRAMEWORK = { + # ВАШИ НАСТРОЙКИ + 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework.authentication.TokenAuthentication', + ], + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.IsAuthenticated', + ] +} diff --git a/testapi/urls.py b/testapi/urls.py new file mode 100644 index 0000000..52a2cd2 --- /dev/null +++ b/testapi/urls.py @@ -0,0 +1,27 @@ +""" +URL configuration for testapi project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.1/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 +from drf_spectacular.views import SpectacularAPIView +from drf_spectacular.views import SpectacularSwaggerView + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include('api.urls')), + path('api/schema/', SpectacularAPIView.as_view(), name='schema'), + path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='docs'), +] diff --git a/testapi/wsgi.py b/testapi/wsgi.py new file mode 100644 index 0000000..e6b51be --- /dev/null +++ b/testapi/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for testapi 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.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapi.settings') + +application = get_wsgi_application()