first commit

This commit is contained in:
afanasyev.aa 2025-04-04 18:16:08 +09:00
parent 6bdba48fa5
commit 7f28fe580d
38 changed files with 452 additions and 0 deletions

0
api/__init__.py Normal file
View file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

7
api/admin.py Normal file
View file

@ -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)

6
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'

38
api/build_qstring.py Normal file
View file

@ -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)

View file

@ -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)),
],
),
]

View file

@ -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',
),
]

View file

Binary file not shown.

20
api/models.py Normal file
View file

@ -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')

7
api/serializers.py Normal file
View file

@ -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']

10
api/tests.py Normal file
View file

@ -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()

10
api/urls.py Normal file
View file

@ -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/<uuid:pk>', PredictionDeleteView.as_view(), name='delete_prediction'),
path('api/token/', obtain_auth_token),
]

63
api/views.py Normal file
View file

@ -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]

BIN
db.sqlite3 Normal file

Binary file not shown.

22
manage.py Normal 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', '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()

0
testapi/__init__.py Normal file
View file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

16
testapi/asgi.py Normal file
View file

@ -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()

142
testapi/settings.py Normal file
View file

@ -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',
]
}

27
testapi/urls.py Normal file
View file

@ -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'),
]

16
testapi/wsgi.py Normal file
View file

@ -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()