paramecio2fm/paramecio2/libraries/db/extrafields/dictfield.py
2025-04-21 13:33:35 +02:00

87 lines
2.5 KiB
Python

"""
Paramecio2fm is a series of wrappers for Flask, mako and others and construct a simple headless cms.
Copyright (C) 2023 Antonio de la Rosa Caballero
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from paramecio2.libraries.db.webmodel import WebModel, PhangoField
import json
class DictField(PhangoField):
"""Field for save json dicts with determined values"""
def __init__(self, name, field_type, required=False):
"""
Args:
name (str): The name of field
field_type (PhangoField): The type of PhangoField for save in ArrayField
required (bool): Boolean for define if field is required or not
"""
super().__init__(name, required)
self.field_type=field_type
self.error_default='Sorry, the json dict is invalid'
self.set_default='NOT NULL'
self.type_sql='longtext'
self.jtype='object'
self.default_value='{}'
def check(self, value):
if type(value).__name__=='str':
try:
value=json.loads(value)
except json.JSONDecodeError:
value={}
self.error=True
self.txt_error=self.error_default
elif type(value).__name__!='dict':
value={}
self.error=True
self.txt_error=self.error_default
error=0
for k,v in value.items():
value[k]=self.field_type.check(v)
if self.field_type.error:
error+=1
final_value=json.dumps(value)
if error>0:
self.error=True
#final_value=WebModel.escape_sql(final_value)
return final_value
def get_type_sql(self):
return 'JSON '+self.set_default
def show_formatted(self, value):
return ", ".join(value)