Fixes for json and added responsesapi

This commit is contained in:
Antonio de la Rosa 2025-04-16 02:00:14 +02:00
parent a0d7a8a3e0
commit eb593fb9b2
5 changed files with 175 additions and 21 deletions

View file

@ -40,7 +40,7 @@ class IntegerField(PhangoField):
self.default_value=0
self.jtype='integer'
self.jformat='int64'
self.jexample='12345'
self.jexample='1'
self.type_sql='int({})'.format(self.size)

View file

@ -42,6 +42,8 @@ class ArrayField(PhangoField):
self.type_sql='text'
self.jtype='array'
self.default_value='[]'
def check(self, value):
@ -50,13 +52,13 @@ class ArrayField(PhangoField):
value=json.loads(value)
except json.JSONDecodeError:
value=[]
value={}
self.error=True
self.txt_error=self.error_default
elif type(value).__name__!='list':
value=[]
value={}
self.error=True
self.txt_error='Sorry, the json array is invalid'
@ -80,7 +82,7 @@ class ArrayField(PhangoField):
def get_type_sql(self):
return 'JSON'
return 'JSON DEFAULT "{}"'
def show_formatted(self, value):

View file

@ -42,6 +42,8 @@ class DictField(PhangoField):
self.type_sql='longtext'
self.jtype='object'
self.default_value='{}'
def check(self, value):

View file

@ -1,3 +1,22 @@
"""
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/>.
"""
#By default id is not showed
from paramecio.libraries.pages import Pages
@ -15,9 +34,47 @@ gtext=PGetText(__file__)
_=gtext.gettext
class SimpleList:
"""Class for create item list from a model table
"""
def __init__(self, model, url, t):
"""Class for create item list from a model table
You can create lists using a WebModel. You can select the show fields, and you have features how order by field and simple searchs.
Args:
model (WebModel): A WebModel model (equivalent to database mysql table)
url (str): A string with the base url for the forms.
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
Attributes:
raw_query (boolean): If True then raw query is done, if False then query with all related fields is done
t (PTemplate): Template used for the class. Normally template subclassed from admin_t PTemplate
model (WebModel): The webmodel used for generate the admin model form
fields (list): A list with fields names of model getting of db query
fields_showed (list): A list with fields names of model showed in list
url (str): Base url used by SimpleList for generate edit, insert and other urls.
limit_pages (int): The number of items by page. By default, 20 items
order_defaults (list): Internal list used for define Ascendent and Descendent in sql queries
order_class (list): Internal list used for show icons for ascendent or descendent field selection
order (str): Default order used in order_defaults list
order_field (str): The default field used for order the list. By default is the model id field
order_by (str): The default order ASC or DESC defined in order_class list. By default is 0 or ASC
change_order (dict): Internal dict used for get all ordenable fields from model
yes_search (boolean): If True, a search form is showed, if False, the search form is hidden.
search_text (str): Used for save the search text sended via POST.
initial_num_pages (int): Initial number of pages showed in pagination.
table_div (boolean): If True, use div for create the table, if False, use standard html table for create the table.
begin_page (int): Number that is used for begin the elements to get from query
search_fields (list): The fields used for search data in form.
arr_extra_fields (list): List with the names of extra fields
arr_extra_options (list): List with a set of functions used how extra fields. This functions return lists with different options, joined with jln attribute.
jln (list): Jump line for join options by default.
ajax (boolean): If True, ajax is used for get items for the list and change page, if False, typical httpd request is used for change the items page.
"""
self.raw_query=True
self.getpostfiles=GetPostFiles()
@ -89,9 +146,14 @@ class SimpleList:
self.ajax=False
def restore_fields(self):
"""Simple method for restore default fields from model
"""
self.fields=self.model.fields.keys()
def obtain_order(self):
"""Function for set the order query defaults for list from http request query args.
"""
self.order=self.getpostfiles.get.get('order', self.order)
@ -111,6 +173,8 @@ class SimpleList:
self.order=order_k
def obtain_field_search(self):
"""Function for set the field search query defaults for list from http request query args.
"""
self.order_field=self.getpostfiles.get.get('order_field', self.order_field)
@ -144,6 +208,8 @@ class SimpleList:
#self.order_field=self.order_field
def search(self):
"""Function for set the text order query defaults for list from http request query args.
"""
self.getpostfiles.get['search_text']=self.getpostfiles.get.get('search_text', '')
@ -165,17 +231,32 @@ class SimpleList:
pass
def set_options(self, options_func, arr_row):
#SimpleList.standard_options(arr_row)
"""Method for join options list returns with jln attributte separator
Returns:
options (str): Return a string with joined options
"""
return self.jln.join(options_func(self.url, arr_row[self.model.name_field_id], arr_row))
@staticmethod
def standard_options(url, id, arr_row):
"""Static method for get standar options for make things with the items row.
Returns:
options (list): Return a list of basic options for items row
"""
options=[]
options.append('<a href="'+add_get_parameters(url, op_admin=1, id=id)+'">'+_('Edit')+'</a>')
options.append('<a href="'+add_get_parameters(url, op_admin=3, id=id)+'">'+_('Delete')+'</a>')
return options
def show(self):
"""Method for show the table
The principal method of the class. The list is showed with the selected fields, search form, pagination...
"""
self.model.yes_reset_conditions=False
@ -222,7 +303,7 @@ class SimpleList:
list_items.close()
return listing
"""
@staticmethod
def get_ajax_page(model):
@ -233,11 +314,12 @@ class SimpleList:
pass
"""
class AjaxList(SimpleList):
"""Class for make a list from a table based in Ajax
"""
# Fields example: [[I18n.lang('cuchulu', 'hostname', 'Hostname'), True], ['IP', True], [I18n.lang('cuchulu', 'options', 'Options'), False]]
# Fields example: [['Hostname', True], ['IP', True], ['Options', False]]
# arr_order_fields=['server.hostname', 'server.ip']
@ -248,6 +330,32 @@ class AjaxList(SimpleList):
# str_query_params -> [s['cu_id'], begin_page, limit]
def __init__(self, db, fields, arr_order_fields, count_query, str_query):
"""Class for make a list from a table based in Ajax
A class that is useful for creating listings based on database models using Ajax
Args:
db (sql connection): A MySQL connection used for get the model.
fields (list): A list with the fields showed in table
arr_order_fields (list): A list with the sql names of selected fields for show.
count_query (str): sql segment for count query sentence. Example: select count(id) from table WHERE name=%s
str_query (str): sql segment for query sentence. Example: select id from table WHERE name=%s
Attributes:
fields (list): A list with the fields showed in table
arr_order_fields (list): A list with the sql names of selected fields for show.
limit (int): the number of items selected in query sentence.
count_query (str): sql segment for count query sentence. Example: select count(id) from table WHERE name=%s
count_query_params (list): A list with the params for parse a sql count query with %s symbols (View python help about sql sentences and connectors)
str_query (str): sql segment for query sentence. Example: select id from table WHERE name=%s
str_query_params (list): A list with the params for parse a sql query with %s symbols (View python help about sql sentences and connectors)
initial_num_pages (int): Initial number of pages showed in pagination.
db (sql connection): A MySQL connection used for get the model.
func_fields (dict): A series of functions used for a series of extra fields referring to each row of the table
initial_order_field (str): FIeld used for order the table in first execution
initial_order (int): If 0, the initial order is Ascendent, if 1, the initial order is Descendent.
"""
self.fields=fields
self.arr_order_fields=arr_order_fields
@ -260,19 +368,20 @@ class AjaxList(SimpleList):
self.db=db
self.func_fields={}
self.initial_order_field=''
self.initial_order=0
def show(self):
"""Method for show the table
p=GetPostFiles()
p.obtain_query()
The principal method of the class. The list is showed with the selected fields, search form, pagination...
"""
p.obtain_post(required_post=[], ignore_csrf_token=True)
begin_page=int(p.post.get('position', 0))
order_field=p.post.get('order_field', '')
order=p.post.get('order', 0)
begin_page=int(request.query.get('position', 0))
order_field=request.query.get('order_field', self.initial_order_field)
order=request.query.get('order', self.initial_order)
limit=self.limit
arr_order=['ASC', 'DESC']
order_sql=''
@ -307,11 +416,10 @@ class AjaxList(SimpleList):
html_pages=''
if self.limit>0:
str_query+=' limit %s, %s'
str_query+=' limit %s, %s'
params.append(begin_page)
params.append(limit)
pages=Pages()
html_pages=_('Pages')+': '+pages.show( begin_page, total_elements, limit, '#' ,initial_num_pages=self.initial_num_pages, variable='begin_page', label='', func_jscript='')
@ -336,5 +444,7 @@ class AjaxList(SimpleList):
return {'fields': self.fields, 'rows': rows, 'html_pages': html_pages}
class SimpleAjaxList():
pass

View file

@ -0,0 +1,40 @@
from paramecio.libraries.db import corefields
from paramecio.libraries.db.extrafields.jsonfield import JsonField
try:
import ujson as json
except:
import json
"""A class for list objects with data fields
"""
class ListItem:
pass
"""Typical item """
class Items(ListItem):
name=corefields.CharField('name')
class ResponseItems:
error=corefields.BooleanField('error')
message=corefields.CharField('message')
code_error=corefields.IntegerField('code_error')
#items=JsonField('items', corefields.CharField)
def __init__(self, error=0, message='', code_error=0):
self.error=error
self.message=message
self.code_error=code_error
def toDict(self):
return self.__dict__
def toJSON(self):
return json.dumps( self, default=lambda o: o.__dict__, sort_keys=True, indent=4 )