|
| 1 | +# coding=utf-8 |
| 2 | +""" |
| 3 | + @project: MaxKB |
| 4 | + @Author:虎 |
| 5 | + @file: valid_serializers.py |
| 6 | + @date:2024/7/8 18:00 |
| 7 | + @desc: |
| 8 | +""" |
| 9 | +import re |
| 10 | + |
| 11 | +from django.core import validators |
| 12 | +from django.core.cache import cache |
| 13 | +from django.db.models import QuerySet |
| 14 | +from rest_framework import serializers |
| 15 | + |
| 16 | +from application.models import Application |
| 17 | +from common.constants.cache_version import Cache_Version |
| 18 | +from common.exception.app_exception import AppApiException |
| 19 | +from knowledge.models import Knowledge |
| 20 | +from users.models import User |
| 21 | +from django.utils.translation import gettext_lazy as _ |
| 22 | + |
| 23 | +model_message_dict = { |
| 24 | + 'dataset': {'model': Knowledge, 'count': 50, |
| 25 | + 'message': _( |
| 26 | + 'The community version supports up to 50 knowledge bases. If you need more knowledge bases, please contact us (https://fit2cloud.com/).')}, |
| 27 | + 'application': {'model': Application, 'count': 5, |
| 28 | + 'message': _( |
| 29 | + 'The community version supports up to 5 applications. If you need more applications, please contact us (https://fit2cloud.com/).')}, |
| 30 | + 'user': {'model': User, 'count': 2, |
| 31 | + 'message': _( |
| 32 | + 'The community version supports up to 2 users. If you need more users, please contact us (https://fit2cloud.com/).')} |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +class ValidSerializer(serializers.Serializer): |
| 37 | + valid_type = serializers.CharField(required=True, label=_('type'), validators=[ |
| 38 | + validators.RegexValidator(regex=re.compile("^application|knowledge|user$"), |
| 39 | + message="类型只支持:application|knowledge|user", code=500) |
| 40 | + ]) |
| 41 | + valid_count = serializers.IntegerField(required=True, label=_('check quantity')) |
| 42 | + |
| 43 | + def valid(self, is_valid=True): |
| 44 | + if is_valid: |
| 45 | + self.is_valid(raise_exception=True) |
| 46 | + model_value = model_message_dict.get(self.data.get('valid_type')) |
| 47 | + license_is_valid = cache.get(Cache_Version.SYSTEM.get_key(key='license_is_valid'), |
| 48 | + version=Cache_Version.SYSTEM.get_version()) |
| 49 | + is_license_valid = license_is_valid if license_is_valid is not None else False |
| 50 | + if not is_license_valid: |
| 51 | + if self.data.get('valid_count') != model_value.get('count'): |
| 52 | + raise AppApiException(400, model_value.get('message')) |
| 53 | + if QuerySet( |
| 54 | + model_value.get('model')).count() >= model_value.get('count'): |
| 55 | + raise AppApiException(400, model_value.get('message')) |
| 56 | + return True |
0 commit comments