This commit is contained in:
zakhy 2025-01-27 10:30:43 +07:00
parent 82bf397f75
commit 7103399ca6
11 changed files with 121 additions and 114 deletions

View File

@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name='versioning app',
version='1.0.0.5',
version='1.0.1.0',
packages=find_packages(),
include_package_data=True,
install_requires=[

View File

@ -1,8 +0,0 @@
from django.contrib import admin
from versioning.models import UpdateLog
@admin.register(UpdateLog)
class UpdateLogAdmin(admin.ModelAdmin):
pass

View File

@ -1,63 +1,62 @@
import traceback
import os
import json
import importlib
from django.apps import AppConfig
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from versioning.utils import call_func_from_path
class VersioningConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'versioning'
default_auto_field = "django.db.models.BigAutoField"
name = "versioning"
def __init__(self, app_name, app_module):
super().__init__(app_name, app_module)
self.GET_VERSION_FROM_DB_FUNCTION = None
self.ON_UPDATE_FUNCTION = None
def ready(self):
from versioning.models import UpdateLog
version_from_file = self.get_settings_from_file()
version_from_db = call_func_from_path(
self.GET_VERSION_FROM_DB_FUNCTION)
# Получение пути к файлу
update_file_path = getattr(settings, 'UPDATE_FILE_PATH', None)
if not update_file_path:
# Если пути нет, то вызываем ошибку
raise ImproperlyConfigured('The UPDATE_FILE_PATH variable is not set')
if version_from_file != version_from_db:
call_func_from_path(self.ON_UPDATE_FUNCTION)
if not os.path.exists(update_file_path):
# Если нет файла - возврат из функции
return
def get_setting(self, name: str, is_function: bool,
default: str | None = None):
value = getattr(settings, name, default)
if value is None:
raise ImproperlyConfigured(f"Настройка {name} не установлена")
if is_function:
setattr(self, name, value)
return value
with open(update_file_path, 'r') as file:
try:
# Попытка считать файл
update_info = json.load(file)
except Exception:
print(traceback.format_exc())
# Если файл не json - вызываем ошибку
raise ImproperlyConfigured('The file content must be valid json')
try:
# Попытка создать объект из файла
update_log_obj = UpdateLog.objects.create(**update_info)
except Exception:
# Если содержимое файла не подходит под формат модели - вызываем ошибку
os.remove(update_file_path)
print(traceback.format_exc())
raise ImproperlyConfigured('The file does not match format')
def get_settings_from_file(self):
# Имя настройки, которая хранит версию. По умолчанию APP_VERSION
setting_version_name = self.get_setting(
"VERSION_SETTING_NAME",
False,
"APP_VERSION"
)
callback_function = getattr(settings, 'VERSION_UPDATE_CALLBACK', None)
if callback_function:
# Если функция-callback задана, то вызываем ее
call_version_update_callback(callback_function,
update_log_obj.date_release,
update_log_obj.version,
update_log_obj.description)
os.remove(update_file_path)
# Получение версии из файла
version_from_file = self.get_setting(setting_version_name, False)
# Функция для получения версии из БД
self.get_setting(
"GET_VERSION_FROM_DB_FUNCTION",
True,
"versioning.example.mock_function.echo_version"
)
# Функция для обновления
self.get_setting(
"ON_UPDATE_FUNCTION",
True,
"versioning.example.mock_function.print_update"
)
return version_from_file
def call_version_update_callback(callback_path, date_release, version, description):
try:
# Попытка выполнить функцию
module_name, function_name = callback_path.rsplit('.', 1)
module = importlib.import_module(module_name)
callback_function = getattr(module, function_name)
callback_function(date_release, version, description)
except Exception as e:
print('error while callback:', traceback.format_exc())

View File

@ -0,0 +1,10 @@
from django.conf import settings
def echo_version():
# return getattr(settings, "APP_VERSION", "")
return "0.9.2"
def print_update():
print("Версия в БД отличается от версии в файле. Производим обновление")
return 0

View File

@ -0,0 +1,16 @@
# Generated by Django 3.2.25 on 2025-01-27 10:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('versioning', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='UpdateLog',
),
]

View File

@ -1,18 +0,0 @@
import datetime
from django.db import models
from django.utils import timezone
class UpdateLog(models.Model):
version = models.TextField(unique=True, verbose_name='Версия')
description = models.TextField(verbose_name='Описание')
date_release = models.DateField(verbose_name='Дата релиза')
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Время обновления')
def __str__(self):
return f'{self.version} {self.date_release}'
class Meta:
verbose_name = 'Обновление'
verbose_name_plural = 'Обновления'

View File

@ -1,21 +1,21 @@
from versioning.models import UpdateLog
import markdown
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
@stringfilter
def render_markdown(value):
md = markdown.Markdown(extensions=["fenced_code"])
return mark_safe(md.convert(value))
@register.inclusion_tag('versioning/_changelog.html')
def render_changelog():
updatelogs = UpdateLog.objects.all().order_by('-date_release')
return {'updatelogs': updatelogs}
# from versioning.models import UpdateLog
# import markdown
#
# from django import template
# from django.template.defaultfilters import stringfilter
# from django.utils.safestring import mark_safe
#
# register = template.Library()
#
#
# @register.filter
# @stringfilter
# def render_markdown(value):
# md = markdown.Markdown(extensions=["fenced_code"])
# return mark_safe(md.convert(value))
#
#
# @register.inclusion_tag('versioning/_changelog.html')
# def render_changelog():
# updatelogs = UpdateLog.objects.all().order_by('-date_release')
# return {'updatelogs': updatelogs}

View File

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

View File

@ -1,9 +1,9 @@
from django.urls import path
from versioning.views import updatelog_list
# from versioning.views import updatelog_list
app_name = 'versioning'
urlpatterns = [
path('', updatelog_list, name='updatelog_list')
# path('', updatelog_list, name='updatelog_list')
]

View File

@ -1,5 +1,16 @@
from .models import UpdateLog
import importlib
import traceback
def get_latest_version():
return UpdateLog.objects.latest('created_at')
def call_func_from_path(func_path, *args, **kwargs):
try:
# Попытка выполнить функцию
module_name, function_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_name)
callback_function = getattr(module, function_name)
return callback_function(*args, **kwargs)
except Exception as e:
print("Ошибка во время выполнения:",
traceback.format_exc())

View File

@ -1,9 +1,9 @@
import markdown
from django.shortcuts import render
from versioning.models import UpdateLog
def updatelog_list(request):
qs = UpdateLog.objects.all()
return render(request, 'versioning/changelog.html', {'updatelogs': qs})
# import markdown
# from django.shortcuts import render
#
# from versioning.models import UpdateLog
#
#
# def updatelog_list(request):
# qs = UpdateLog.objects.all()
# return render(request, 'versioning/changelog.html', {'updatelogs': qs})