def expmng_main(self, explorers): explorer_to_create = splitAndStrip(explorers, ',') pane = self.pageSource() pg = pane.paletteGroup('gnr_explorer', title='!!Explorers', dockTo='pbl_dock') for explorer in explorer_to_create: explorer_pars = None if ' AS ' in explorer: explorer, explorer_code = splitAndStrip(explorer, ' AS ') elif ' as ' in explorer: explorer, explorer_code = splitAndStrip(explorer, ' as ') else: explorer_code = None if ':' in explorer: explorer, explorer_pars = explorer.split(':', 1) if not explorer_code: explorer_code = explorer.replace('.', '_').replace('@', '_') handler = getattr(self, 'explorer_' + explorer, None) if handler: data, metadata = handler(explorer_pars, explorer_code=explorer_code) else: if explorer_pars: explorer_pars = fromJson(explorer_pars.replace("'", '"')) kw = dict() for k, v in explorer_pars.items(): kw[str(k)] = v else: kw = dict() data, metadata = self.expmng_htableExplorer(explorer_table=explorer, **kw) pg.paletteTree(explorer_code, title=metadata.pop('title', explorer), data=data, **metadata)
def gridFilterBox(self, pane, gridId=None, datapath=None, filterOn=None, table=None, **kwargs): fltList = splitAndStrip(filterOn, ',') cols = [] for col in fltList: caption = None if ':' in col: caption, col = col.split(':') if not caption: caption = self.db.table(table).column(col).name_long colList = splitAndStrip(col, '+') col = '+'.join([self.db.colToAs(c) for c in colList]) cols.append('%s:%s' % (caption, col)) self.filterBox(pane.div(float='right', margin_right='5px'), filterOn=','.join(cols), datapath=datapath or '.filter', **kwargs) filtercontroller = pane.dataController(datapath=".filter") filtercontroller.dataController( 'genro.wdgById(gridId).applyFilter(value,null,field);', gridId=gridId, value="^.current_value", field='=.field') filtercontroller.dataController( 'genro.wdgById(gridId).applyFilter("",null,field);', gridId=gridId, field='^.field')
def get_page_class(self, path=None, pkg=None): """add??? :param path: add???. Default value is ``None`` :param pkg: add???. Default value is ``None`` :returns: add??? """ if pkg == '*': module_path = os.path.join(self.site_path, path) pkg = self.site.config['packages?default'] else: module_path = os.path.join(self.gnrapp.packages[pkg].packageFolder, 'webpages', path) # if module_path in self.page_factories: # return self.page_factories[module_path] page_module = gnrImport(module_path, avoidDup=True) page_factory = getattr(page_module, 'page_factory', GnrWebPage) custom_class = getattr(page_module, 'GnrCustomWebPage') py_requires = splitAndStrip(getattr(custom_class, 'py_requires', ''), ',') plugin_webpage_classes = self.plugin_webpage_classes(path, pkg=pkg) for plugin_webpage_class in plugin_webpage_classes: plugin_py_requires = splitAndStrip(getattr(plugin_webpage_class, 'py_requires', ''), ',') py_requires.extend(plugin_py_requires) page_class = cloneClass('GnrCustomWebPage', page_factory) page_class.__module__ = page_module self.page_class_base_mixin(page_class, pkg=pkg) page_class.dojo_version = getattr(custom_class, 'dojo_version', None) or self.site.config[ 'dojo?version'] or '11' page_class.theme = getattr(custom_class, 'theme', None) or self.site.config['dojo?theme'] or 'tundra' page_class.gnrjsversion = getattr(custom_class, 'gnrjsversion', None) or self.site.config[ 'gnrjs?version'] or '11' page_class.maintable = getattr(custom_class, 'maintable', None) page_class.recordLock = getattr(custom_class, 'recordLock', None) page_class.user_polling = int( getattr(custom_class, 'user_polling', None) or self.site.config['polling?user'] or 3) page_class.auto_polling = int( getattr(custom_class, 'auto_polling', None) or self.site.config['polling?auto'] or 30) page_class.eagers = getattr(custom_class, 'eagers', {}) page_class.css_requires = [] page_class.js_requires = splitAndStrip(getattr(custom_class, 'js_requires', ''), ',') page_class.pageOptions = getattr(custom_class, 'pageOptions', {}) page_class.auth_tags = getattr(custom_class, 'auth_tags', '') page_class.resourceDirs = self.page_class_resourceDirs(page_class, module_path, pkg=pkg) self.page_pyrequires_mixin(page_class, py_requires) classMixin(page_class, custom_class, only_callables=False) page_class.css_requires.extend([x for x in splitAndStrip(getattr(custom_class, 'css_requires', ''), ',') if x]) page_class.tpldirectories = page_class.resourceDirs + [ self.gnr_static_handler.path(page_class.gnrjsversion, 'tpl')] page_class._packageId = pkg self.page_class_plugin_mixin(page_class, plugin_webpage_classes) self.page_class_custom_mixin(page_class, path, pkg=pkg) self.page_factories[module_path] = page_class return page_class
def _prepareColumnsAndGroupBy(self, columns, group_by): columns = columns.replace(' (', '(') columns_list = splitAndStrip(columns) group_list = [c for c in columns_list if not (c.startswith('COUNT(') or c.startswith('count(') or c.startswith('SUM(') or c.startswith('sum(') or c.startswith('AVG(') or c.startswith('avg('))] if len(columns_list) > len(group_list): group_by = splitAndStrip(group_by) or [] for g in group_list: if g and not g in group_by: group_by.append(g) group_by = ','.join(group_by).strip(',') columns = ','.join(columns_list).strip(',') return group_by, columns
def calculate_style(self, attr, um, **kwargs): """add??? :param attr: add??? :param um: add??? """ style = attr.pop('style', '') style = style.replace('\n', '') style_dict = dict([(splitAndStrip(x, ':')) for x in style.split(';') if ':' in x]) style_dict.update(kwargs) for name in ('width', 'height', 'top', 'left', 'right', 'bottom'): if name in attr: value = attr.pop(name) try: value = float(value) i_value = int(value) if i_value == value: value = i_value value = '%s%s' % (value, um) except: pass style_dict[name] = value attr['style'] = ''.join( ['%s:%s;' % (k, v) for k, v in style_dict.items()])
def py_requires_iterator(self, source_class, target_class): """add??? :param source_class: add??? :param target_class: add??? """ resourceDirs = target_class.resourceDirs py_requires = [ x for x in splitAndStrip(getattr(source_class, 'py_requires', ''), ',') if x ] or [] for path in py_requires: if ':' in path: modName, clsName = path.split(':') else: modName, clsName = path, '*' modPathList = self.getResourceList(resourceDirs, modName, 'py') or [] if modPathList: modPathList.reverse() for modPath in modPathList: yield '%s:%s' % (modPath, clsName) #classMixin(kls,'%s:%s'%(modPath,clsName),only_callables=False,site=self) else: raise GnrMixinError('Cannot import component %s' % modName)
def build_lazydoc(self,lazydoc,ext=None): ext = ext.replace('.','') if ext else None table,pkey,method = gnrstring.splitAndStrip(lazydoc,sep=',',fixed=3) dflt_method = 'create_cached_document_%s' %ext if ext else 'create_cached_document' m = getattr(self.site.db.table(table),(method or dflt_method),None) if m: result = m(pkey) return result is not False
def setTagChildren(self, record_data, old_record_data=None): """add??? :param record_data: add??? :param old_record_data: add???. Default value is ``None`` :returns: add??? """ tablename = record_data['tablename'] parentTag = record_data['tag'] parentDescription = record_data['description'] oldChildren = {} if old_record_data: #updating parentTag_old = old_record_data['tag'] parentDescription_old = old_record_data['description'] if parentTag_old != parentTag: #updating if change parentTag def cb_tag(row): row['tag'] = row['tag'].replace('%s_' % parentTag_old, '%s_' % parentTag) row['maintag'] = parentTag self.batchUpdate(cb_tag, where='$maintag =:p_tag AND tablename=:t_name', p_tag=parentTag_old, t_name=tablename) if old_record_data and old_record_data['values']: #updating if change change values for item in splitAndStrip(old_record_data['values'], ','): tag, description = splitAndStrip('%s:%s' % (item, item), ':', n=2, fixed=2) oldChildren['%s_%s' % (parentTag, tag)] = description for item in splitAndStrip(record_data['values'], ','): tag, description = splitAndStrip('%s:%s' % (item, item), ':', n=2, fixed=2) fulltag = '%s_%s' % (parentTag, tag) if fulltag in oldChildren: if description != oldChildren[fulltag]: def cb_desc(row): row['description'] = description self.batchUpdate(cb_desc, where='$tag=:c_tag', c_tag=fulltag) oldChildren.pop(fulltag) else: self.insert(Bag( dict(tablename=tablename, tag=fulltag, description=description, maintag=parentTag, subtag=tag))) tagsToDelete = oldChildren.keys() if tagsToDelete: self.deleteSelection('tag', tagsToDelete, condition_op='IN')
def child(self, tag, childname='*_#', childcontent=None, content=None,_parentTag=None, _attributes=None, _returnStruct=True, _position=None, **kwargs): """Set a new item of the ``tag`` type into the current structure. Return the new structure if content is ``None``, else the parent :param tag: structure type :param name: structure name :param content: optional structure content :param _parentTag: TODO :param _attributes: TODO :param childname: the :ref:`childname` """ where = self if childname and childname != '*_#': kwargs['_childname'] = childname if childcontent is None: childcontent = content if _attributes: kwargs.update(_attributes) if '_content' in kwargs: kwargs['content'] = kwargs.pop('_content') if not childname: childname = '*_#' if '.' in childname: namelist = childname.split('.') childname = namelist.pop() for label in namelist: if not label in where: item = self.__class__() where[label] = item where = where[label] childname = childname.replace('*', tag or 'notag').replace('#', str(len(where))) if childcontent is None and _returnStruct: childcontent = self.__class__() result = childcontent else: result = None if _parentTag: if isinstance(_parentTag, basestring): _parentTag = gnrstring.splitAndStrip(_parentTag, ',') actualParentTag = where.getAttr('', tag) if not actualParentTag in _parentTag: raise GnrStructureError('%s "%s" cannot be inserted in a %s' % (tag, childname, actualParentTag)) if childname in where and where[childname] != '' and where[childname] is not None: if where.getAttr(childname, 'tag') != tag: raise GnrStructureError( 'Cannot change %s from %s to %s' % (childname, where.getAttr(childname, 'tag'), tag)) else: kwargs = dict( [(k, v) for k, v in kwargs.items() if v != None]) # default kwargs don't clear old attributes result = where[childname] result.attributes.update(**kwargs) else: where.setItem(childname, childcontent, tag=tag, _position=_position,_attributes=kwargs) return result
def _prepareColumnsAndGroupBy(self, columns, group_by): columns = columns.replace(' (', '(') columns_list = splitAndStrip(columns) group_list = [ c for c in columns_list if not (c.startswith('COUNT(') or c.startswith('count(') or c.startswith('SUM(') or c.startswith('sum(') or c.startswith('AVG(') or c.startswith('avg(')) ] if len(columns_list) > len(group_list): group_by = splitAndStrip(group_by) or [] for g in group_list: if g and not g in group_by: group_by.append(g) group_by = ','.join(group_by).strip(',') columns = ','.join(columns_list).strip(',') return group_by, columns
def __on_class_mixin__(cls, _mixintarget, **kwargs): js_requires = [x for x in splitAndStrip(getattr(cls, 'js_requires', ''), ',') if x] css_requires = [x for x in splitAndStrip(getattr(cls, 'css_requires', ''), ',') if x] namespace = getattr(cls, 'namespace', None) if namespace: if not hasattr(_mixintarget, 'struct_namespaces'): _mixintarget.struct_namespaces = set() _mixintarget.struct_namespaces.add(namespace) if css_requires and not hasattr(_mixintarget, 'css_requires'): _mixintarget.css_requires=[] for css in css_requires: if css and not css in _mixintarget.css_requires: _mixintarget.css_requires.append(css) if js_requires and not hasattr(_mixintarget, 'js_requires'): _mixintarget.js_requires=[] for js in js_requires: if js and not js in _mixintarget.js_requires: _mixintarget.js_requires.append(js)
def __onmixin__(self, _mixinsource, site=None): js_requires = splitAndStrip(getattr(_mixinsource, 'js_requires', ''), ',') css_requires = splitAndStrip(getattr(_mixinsource, 'css_requires', ''), ',') py_requires = splitAndStrip(getattr(_mixinsource, 'py_requires', ''), ',') for css in css_requires: if css and not css in self.css_requires: self.css_requires.append(css) for js in js_requires: if js and not js in self.js_requires: self.js_requires.append(js) #self.css_requires.extend(css_requires) #self.js_requires.extend(js_requires) if py_requires: if site: site.page_pyrequires_mixin(self, py_requires) elif hasattr(self, '_pyrequiresMixin'): self._pyrequiresMixin(py_requires)
def _prepareFilterMenu(self, filterOn): colsMenu = Bag() fltList = splitAndStrip(filterOn, ',') for i,col in enumerate(fltList): caption = col if ':' in col: caption, col = col.split(':') colsMenu.setItem('r%i'%i, None,col=col, caption=caption, childcontent='') return colsMenu
def styleMaker(self, attr): """TODO :param attr: TODO""" style = attr.pop('style', '') style = style.replace('\n', '') style_dict = dict([(splitAndStrip(x, ':')) for x in style.split(';') if ':' in x]) for oneattr in attr.keys(): if oneattr in self.styleAttrNames or ('_' in oneattr and oneattr.split('_')[0] in self.styleAttrNames): style_dict[oneattr.replace('_', '-')] = attr.pop(oneattr) attr['style'] = ''.join(['%s:%s;' % (k, v) for k, v in style_dict.items()])
def build_lazydoc(self, lazydoc, ext=None): ext = ext.replace('.', '') if ext else None table, pkey, method = gnrstring.splitAndStrip(lazydoc, sep=',', fixed=3) dflt_method = 'create_cached_document_%s' % ext if ext else 'create_cached_document' m = getattr(self.site.db.table(table), (method or dflt_method), None) if m: self.site.currentPage = self.site.dummyPage result = m(pkey) return result is not False
def updateFromExternalDb(self,externaldb,empty_before=None): """add??? :param externaldb: add??? :param empty_before: add???. Default value is ``None`` :returns: add??? """ tables = self.attributes.get('export_order') or '' self.db.setConstraintsDeferred() for tbl in splitAndStrip(tables): self.db.table(tbl).copyToDb(externaldb,self.db,empty_before=empty_before)
def gridFilterBox(self, pane, gridId=None, datapath=None, filterOn=None, table=None, **kwargs): fltList = splitAndStrip(filterOn, ',') cols = [] for col in fltList: caption = None if ':' in col: caption, col = col.split(':') if not caption: caption = self.db.table(table).column(col).name_long colList = splitAndStrip(col, '+') col = '+'.join([self.db.colToAs(c) for c in colList]) cols.append('%s:%s' % (caption, col)) self.filterBox(pane.div(float='right', margin_right='5px'), filterOn=','.join(cols), datapath=datapath or '.filter', **kwargs) filtercontroller = pane.dataController(datapath=".filter") filtercontroller.dataController('genro.wdgById(gridId).applyFilter(value,null,field);', gridId=gridId, value="^.current_value", field='=.field') filtercontroller.dataController('genro.wdgById(gridId).applyFilter("",null,field);', gridId=gridId, field='^.field')
def mailLog(self, subject): subject = "[GENROPY_LOG] %s" % subject mailhost = self.attributes.get('smtp_server') fromaddr = self.attributes.get('emails_db_from') toaddrs = gnrstring.splitAndStrip( self.attributes.get('emails_db_manager', ''), ',') if mailhost and toaddrs: if ':' in mailhost: mailhost = mailhost.split(':') mailhandler = SMTPHandler(mailhost, fromaddr, toaddrs, subject) mailhandler.setLevel(logging.ERROR) logging.getLogger('').addHandler(mailhandler)
def updateFromExternalDb(self, externaldb, empty_before=None): """add??? :param externaldb: add??? :param empty_before: add???. Default value is ``None`` :returns: add??? """ tables = self.attributes.get('export_order') or '' self.db.setConstraintsDeferred() for tbl in splitAndStrip(tables): self.db.table(tbl).copyToDb(externaldb, self.db, empty_before=empty_before)
def _prepareFilterMenu(self, filterOn): colsMenu = Bag() fltList = splitAndStrip(filterOn, ',') for i, col in enumerate(fltList): caption = col if ':' in col: caption, col = col.split(':') colsMenu.setItem('r%i' % i, None, col=col, caption=caption, childcontent='') return colsMenu
def test_splitAndStrip(): """docstring for test_splitAndStrip""" assert gnrstring.splitAndStrip('cola, beer, milk') == ['cola', 'beer', 'milk'] assert gnrstring.splitAndStrip('cola, beer, milk', n=1) == ['cola', 'beer, milk'] assert gnrstring.splitAndStrip('cola, beer, milk', fixed=1) == ['cola'] assert gnrstring.splitAndStrip('cola, beer, milk', fixed=5) == ['cola', 'beer', 'milk', '', ''] assert gnrstring.splitAndStrip('cola, beer, milk', fixed=-5) == ['', '', 'cola', 'beer', 'milk'] assert gnrstring.splitAndStrip('cola, beer, milk', fixed=5, n=1) == ['cola', 'beer, milk', '', '', '']
def styleMaker(self, attr): """TODO :param attr: TODO""" style = attr.pop('style', '') style = style.replace('\n', '') style_dict = dict([(splitAndStrip(x, ':')) for x in style.split(';') if ':' in x]) for oneattr in attr.keys(): if oneattr in self.styleAttrNames or ('_' in oneattr and oneattr.split('_')[0] in self.styleAttrNames): style_dict[oneattr.replace('_', '-')] = attr.pop(oneattr) attr['style'] = ''.join( ['%s:%s;' % (k, v) for k, v in style_dict.items()])
def columnsFromString(self, columns=None): """add??? :param columns: add???. Default value is ``None`` """ result = [] if not columns: return result if isinstance(columns, basestring): columns = gnrstring.splitAndStrip(columns) for col in columns: if not col.startswith('@') and not col.startswith('$'): col = '$%s' % col #FIX result.append(col) return result
def calculate_style(self, attr, um, **kwargs): style = attr.pop('style', '') style = style.replace('\n', '') style_dict = dict([(splitAndStrip(x, ':')) for x in style.split(';') if ':' in x]) style_dict.update(kwargs) for name in ('width', 'height', 'top', 'left', 'right', 'bottom'): if name in attr: value = attr.pop(name) try: value = float(value) i_value = int(value) if i_value == value: value = i_value value = '%s%s' % (value, um) except: pass style_dict[name] = value attr['style'] = ''.join(['%s:%s;' % (k, v) for k, v in style_dict.items()])
def test_splitAndStrip(): """docstring for test_splitAndStrip""" assert gnrstring.splitAndStrip('cola, beer, milk') == [ 'cola', 'beer', 'milk' ] assert gnrstring.splitAndStrip('cola, beer, milk', n=1) == ['cola', 'beer, milk'] assert gnrstring.splitAndStrip('cola, beer, milk', fixed=1) == ['cola'] assert gnrstring.splitAndStrip( 'cola, beer, milk', fixed=5) == ['cola', 'beer', 'milk', '', ''] assert gnrstring.splitAndStrip( 'cola, beer, milk', fixed=-5) == ['', '', 'cola', 'beer', 'milk'] assert gnrstring.splitAndStrip('cola, beer, milk', fixed=5, n=1) == ['cola', 'beer, milk', '', '', '']
def py_requires_iterator(self, source_class, target_class): """TODO :param source_class: TODO :param target_class: TODO""" resourceDirs = target_class.resourceDirs py_requires = [x for x in splitAndStrip(getattr(source_class, 'py_requires', ''), ',') if x] or [] for path in py_requires: if ':' in path: modName, clsName = path.split(':') else: modName, clsName = path, '*' modPathList = self.getResourceList(resourceDirs, modName, 'py') or [] if modPathList: modPathList.reverse() for modPath in modPathList: yield '%s:%s' % (modPath, clsName) #classMixin(kls,'%s:%s'%(modPath,clsName),only_callables=False,site=self) else: raise GnrMixinError('Cannot import component %s' % modName)
def getProcessesBag(self,items=None,name=None,user=None): if isinstance(items,basestring): items=splitAndStrip(items) def filteredProcess(p): if user and user != p.username: return False return (not name) or re.match(name,p.name) def bagFromProcess(p): d=p.as_dict() d['create_time']=datetime.fromtimestamp(d['create_time']) d['cpu_percent']=d['cpu_percent'] or 0 d['memory_percent']=d['memory_percent'] or 0 if items: d = [(k,d[k]) for k in items if k in d] return Bag(d) return Bag([('p_%s'%p.pid,bagFromProcess(p)) for p in ps.process_iter() if filteredProcess(p)])
def getProcessesBag(self, items=None, name=None, user=None): if isinstance(items, basestring): items = splitAndStrip(items) def filteredProcess(p): if user and user != p.username: return False return (not name) or re.match(name, p.name) def bagFromProcess(p): d = p.as_dict() d['create_time'] = datetime.fromtimestamp(d['create_time']) d['cpu_percent'] = d['cpu_percent'] or 0 d['memory_percent'] = d['memory_percent'] or 0 if items: d = [(k, d[k]) for k in items if k in d] return Bag(d) return Bag([('p_%s' % p.pid, bagFromProcess(p)) for p in ps.process_iter() if filteredProcess(p)])
def child(self, tag, childname=None, childcontent=None, content=None, _parentTag=None, _attributes=None, _returnStruct=True, _position=None, _childcounter=False, **kwargs): """Set a new item of the ``tag`` type into the current structure. Return the new structure if content is ``None``, else the parent :param tag: structure type :param name: structure name :param content: optional structure content :param _parentTag: TODO :param _attributes: TODO :param childname: the :ref:`childname` """ where = self original_childname = childname childname = childname or self.default_childname if childcontent is None: childcontent = content if _attributes: kwargs.update(_attributes) if '_content' in kwargs: kwargs['content'] = kwargs.pop('_content') if '.' in childname: namelist = childname.split('.') childname = namelist.pop() for label in namelist: if not label in where: item = self.__class__() where[label] = item where = where[label] childname = childname.replace('*', tag or 'notag').replace( '#', str(len(where))) if childcontent is None and _returnStruct: childcontent = self.__class__() result = childcontent else: result = None if _childcounter: kwargs['_childcounter'] = len(where) if _parentTag: if isinstance(_parentTag, basestring): _parentTag = gnrstring.splitAndStrip(_parentTag, ',') actualParentTag = where.getAttr('', tag) if not actualParentTag in _parentTag: raise GnrStructureError('%s "%s" cannot be inserted in a %s' % (tag, childname, actualParentTag)) if not original_childname: where.addItem(childname, childcontent, tag=tag, _position=_position, _attributes=kwargs) return result if childname in where and where[childname] != '' and where[ childname] is not None: if where.getAttr(childname, 'tag') != tag: raise GnrStructureError( 'Cannot change %s from %s to %s' % (childname, where.getAttr(childname, 'tag'), tag)) else: # default kwargs don't clear old attributes kwargs = dict([(k, v) for k, v in kwargs.items() if v != None]) result = where[childname] result.attributes.update(**kwargs) else: where.setItem(childname, childcontent, tag=tag, _position=_position, _attributes=kwargs) return result
def get_page_class(self, basepath=None,relpath=None, pkg=None, plugin=None,request_args=None,request_kwargs=None): """TODO :param path: TODO :param pkg: the :ref:`package <packages>` object""" module_path = os.path.join(basepath,relpath) page_module = gnrImport(module_path, avoidDup=True,silent=False) page_factory = getattr(page_module, 'page_factory', GnrWebPage) custom_class = getattr(page_module, 'GnrCustomWebPage') mainPkg = pkg if hasattr(custom_class,'getMainPackage'): kw = dict() if 'page_id' in request_kwargs: kw = self.site.register.pageStore(request_kwargs['page_id']).getItem('pageArgs') or dict() kw.update(request_kwargs) mainPkg = custom_class.getMainPackage(request_args=request_args,request_kwargs=kw) py_requires = splitAndStrip(getattr(custom_class, 'py_requires', ''), ',') plugin_webpage_classes = self.plugin_webpage_classes(relpath, pkg=mainPkg) for plugin_webpage_class in plugin_webpage_classes: plugin_py_requires = splitAndStrip(getattr(plugin_webpage_class, 'py_requires', ''), ',') py_requires.extend(plugin_py_requires) page_class = cloneClass('GnrCustomWebPage', page_factory) page_class.__module__ = page_module.__name__ self.page_class_base_mixin(page_class, pkg=mainPkg) package_py_requires = splitAndStrip(getattr(page_class, 'package_py_requires', ''), ',') package_js_requires = splitAndStrip(getattr(page_class, 'package_js_requires', ''), ',') package_css_requires = splitAndStrip(getattr(page_class, 'package_css_requires', ''), ',') if package_py_requires: py_requires = uniquify(package_py_requires + py_requires) page_class.dojo_version = getattr(custom_class, 'dojo_version', None) or self.site.config[ 'dojo?version'] or '11' page_class.theme = getattr(custom_class, 'theme', None) or self.site.config['dojo?theme'] or 'tundra' page_class.gnrjsversion = getattr(custom_class, 'gnrjsversion', None) or self.site.config[ 'gnrjs?version'] or '11' page_class.maintable = getattr(custom_class, 'maintable', None) page_class.recordLock = getattr(custom_class, 'recordLock', None) page_class.user_polling = int( getattr(custom_class, 'user_polling', None) or self.site.config['polling?user'] or 3) page_class.auto_polling = int( getattr(custom_class, 'auto_polling', None) or self.site.config['polling?auto'] or 30) if hasattr(custom_class,'polling_enabled'): page_class.polling_enabled = getattr(custom_class, 'polling_enabled') page_class.eagers = getattr(custom_class, 'eagers', {}) page_class.css_requires = [] page_class.js_requires = splitAndStrip(getattr(custom_class, 'js_requires', ''), ',') if package_js_requires: page_class.js_requires = uniquify(package_js_requires + page_class.js_requires) page_class.pageOptions = getattr(custom_class, 'pageOptions', {}) page_class.auth_tags = getattr(custom_class, 'auth_tags', '') page_class.resourceDirs = self.page_class_resourceDirs(page_class, module_path, pkg=mainPkg) self.page_pyrequires_mixin(page_class, py_requires) classMixin(page_class, custom_class, only_callables=False) page_class.css_requires.extend([x for x in splitAndStrip(getattr(custom_class, 'css_requires', ''), ',') if x]) if package_css_requires: page_class.css_requires = uniquify(page_class.css_requires+package_css_requires) page_class.tpldirectories = page_class.resourceDirs + [ self.gnr_static_handler.path(page_class.gnrjsversion, 'tpl')] page_class._packageId = mainPkg self.page_class_plugin_mixin(page_class, plugin_webpage_classes) self.page_class_custom_mixin(page_class, relpath, pkg=mainPkg) self.page_factories[module_path] = page_class return page_class
def get_page_class(self, path=None, pkg=None): """add??? :param path: add???. Default value is ``None`` :param pkg: add???. Default value is ``None`` :returns: add??? """ if pkg == '*': module_path = os.path.join(self.site_path, path) pkg = self.site.config['packages?default'] else: module_path = os.path.join(self.gnrapp.packages[pkg].packageFolder, 'webpages', path) # if module_path in self.page_factories: # return self.page_factories[module_path] page_module = gnrImport(module_path, avoidDup=True) page_factory = getattr(page_module, 'page_factory', GnrWebPage) custom_class = getattr(page_module, 'GnrCustomWebPage') py_requires = splitAndStrip(getattr(custom_class, 'py_requires', ''), ',') plugin_webpage_classes = self.plugin_webpage_classes(path, pkg=pkg) for plugin_webpage_class in plugin_webpage_classes: plugin_py_requires = splitAndStrip( getattr(plugin_webpage_class, 'py_requires', ''), ',') py_requires.extend(plugin_py_requires) page_class = cloneClass('GnrCustomWebPage', page_factory) page_class.__module__ = page_module self.page_class_base_mixin(page_class, pkg=pkg) page_class.dojo_version = getattr( custom_class, 'dojo_version', None) or self.site.config['dojo?version'] or '11' page_class.theme = getattr( custom_class, 'theme', None) or self.site.config['dojo?theme'] or 'tundra' page_class.gnrjsversion = getattr( custom_class, 'gnrjsversion', None) or self.site.config['gnrjs?version'] or '11' page_class.maintable = getattr(custom_class, 'maintable', None) page_class.recordLock = getattr(custom_class, 'recordLock', None) page_class.user_polling = int( getattr(custom_class, 'user_polling', None) or self.site.config['polling?user'] or 3) page_class.auto_polling = int( getattr(custom_class, 'auto_polling', None) or self.site.config['polling?auto'] or 30) page_class.eagers = getattr(custom_class, 'eagers', {}) page_class.css_requires = [] page_class.js_requires = splitAndStrip( getattr(custom_class, 'js_requires', ''), ',') page_class.pageOptions = getattr(custom_class, 'pageOptions', {}) page_class.auth_tags = getattr(custom_class, 'auth_tags', '') page_class.resourceDirs = self.page_class_resourceDirs(page_class, module_path, pkg=pkg) self.page_pyrequires_mixin(page_class, py_requires) classMixin(page_class, custom_class, only_callables=False) page_class.css_requires.extend([ x for x in splitAndStrip(getattr(custom_class, 'css_requires', ''), ',') if x ]) page_class.tpldirectories = page_class.resourceDirs + [ self.gnr_static_handler.path(page_class.gnrjsversion, 'tpl') ] page_class._packageId = pkg self.page_class_plugin_mixin(page_class, plugin_webpage_classes) self.page_class_custom_mixin(page_class, path, pkg=pkg) self.page_factories[module_path] = page_class return page_class
def remote_getFormTags(self, pane, pkey=None, selectedRowIdx=None, call_mode=None, selectionName=None, queryValues=None, table=None, **kwargs): taglinktbl = self.db.table('%s.recordtag_link' % self.package.name) table = table or self.maintable def lblGetter(fulltag, label): return label if call_mode == 'form': tagbag = taglinktbl.getTagLinksBag(self.maintable, pkey) pane.data('.tagbag', tagbag) elif call_mode == 'list' and selectionName: pkeys = self.getUserSelection( table=table, selectionName=selectionName, selectedRowidx=selectedRowIdx).output('pkeylist') countDict = taglinktbl.getCountLinkDict(table, pkeys) def lblGetter(fulltag, label): if countDict.get(fulltag): return "%s(%i)" % (label, countDict.get(fulltag)['howmany']) return label recordtagtbl = self.db.table('%s.recordtag' % self.package.name) rows = recordtagtbl.query( where='$tablename =:tbl AND $maintag IS NULL', tbl=table, order_by='$values desc,$tag').fetch() externalFrame = pane.div(_class='tag_frame bgcolor_medium', datapath='.tagbag', padding='10px') tag_table = externalFrame.div(style='display:table;width:100%') for j, r in enumerate(rows): values = r['values'] tag = r['tag'] description = r['description'] label_width = '%fem' % ((len(description) * 0.3) + 2) buttons = [] max_width = 3 if values: for val in values.split(','): subtag, label = splitAndStrip('%s:%s' % (val, val), ':', n=2, fixed=2) fulltag = '%s_%s' % (tag, subtag) label = lblGetter(fulltag, label) buttons.append( dict(value='^.%s' % subtag, _class='dijitButtonNode tag_button tag_value', label=label, fulltag=fulltag)) for b in buttons: if len(b['label']) > max_width: max_width = len(b['label']) max_width = '%fem' % ((max_width * .5) + 2) else: label = lblGetter(tag, '!!Yes') buttons.append( dict(value='^.true', _class='dijitButtonNode tag_button tag_true', label=label, fulltag=tag)) oddOrEven = 'even' colorRow = 'bgcolor_bright' if j % 2: oddOrEven = 'odd' colorRow = 'bgcolor_brightest' tag_row = tag_table.div( style='display:table-row', height='5px' ) #no dimensioni riga solo padding dimensioni ai contenuti delle celle tag_row = tag_table.div( style='display:table-row', _class='tag_line tag_%s' % (oddOrEven), datapath='.%s' % tag ) #no dimensioni riga solo padding dimensioni ai contenuti delle celle if call_mode == 'form': label_col = tag_row.div( description, style='display:table-cell', width=label_width, _class= 'tag_left_col tag_label_col bgcolor_darkest color_brightest' ) else: cb_col = tag_row.div( style='display:table-cell', _class='tag_left_col bgcolor_darkest color_brightest', padding_left='10px', width='30px') cb_col.checkbox(value='^.?enabled', validate_onAccept="""if(!value){ var line = GET #; line.walk(function(node){if(node.getValue()){node.setValue(null);}}); SET .?selectedTag = null; }else if(userChange){ SET .?enabled = false; }""") label_col = tag_row.div( description, style='display:table-cell', width=label_width, _class='bgcolor_darkest color_brightest tag_label_col', padding_left='10px') no_td = tag_row.div( style='display:table-cell', _class=colorRow, width='4em').div(_class='dijitButtonNode tag_button tag_false') if call_mode == 'helper' and queryValues: if tag in queryValues['tagged_not']: no_td.data('.false', True) no_td.data('.?enabled', True) no_td.data('.?selectedTag', '!%s' % tag) no_td.radiobutton( value='^.false', label='!!No', group=tag, connect_onclick='SET .?enabled= true; SET .?selectedTag="!%s";' % tag) value_col = tag_row.div(style='display:table-cell', _class='tag_value_col %s' % colorRow) for btn in buttons: value_td = value_col.div(_class=btn['_class'], width=max_width) if call_mode == 'helper' and queryValues: if btn['fulltag'] in queryValues['tagged']: value_td.data(btn['value'][1:], True) value_td.data('.?enabled', True) value_td.data('.?selectedTag', btn['fulltag']) value_td.radiobutton( value=btn['value'], label=btn['label'], group=tag, connect_onclick= 'SET .?enabled= true; SET .?selectedTag="%s";' % btn['fulltag'])
def get_page_class(self, path=None, pkg=None, plugin=None,request_args=None,request_kwargs=None): """TODO :param path: TODO :param pkg: the :ref:`package <packages>` object""" if pkg == '*': module_path = os.path.join(self.site_path, path) pkg = self.site.config['packages?default'] else: if plugin: module_path= os.path.join(self.gnrapp.packages[pkg].plugins[plugin].webpages_path, path) else: module_path = os.path.join(self.gnrapp.packages[pkg].packageFolder, 'webpages', path) # if module_path in self.page_factories: # return self.page_factories[module_path] page_module = gnrImport(module_path, avoidDup=True) page_factory = getattr(page_module, 'page_factory', GnrWebPage) custom_class = getattr(page_module, 'GnrCustomWebPage') mainPkg = pkg if hasattr(custom_class,'getMainPackage'): kw = dict() if 'page_id' in request_kwargs: kw = self.site.register.pageStore(request_kwargs['page_id']).getItem('pageArgs') or dict() kw.update(request_kwargs) mainPkg = custom_class.getMainPackage(request_args=request_args,request_kwargs=kw) py_requires = splitAndStrip(getattr(custom_class, 'py_requires', ''), ',') plugin_webpage_classes = self.plugin_webpage_classes(path, pkg=mainPkg) for plugin_webpage_class in plugin_webpage_classes: plugin_py_requires = splitAndStrip(getattr(plugin_webpage_class, 'py_requires', ''), ',') py_requires.extend(plugin_py_requires) page_class = cloneClass('GnrCustomWebPage', page_factory) page_class.__module__ = page_module.__name__ self.page_class_base_mixin(page_class, pkg=mainPkg) page_class.dojo_version = getattr(custom_class, 'dojo_version', None) or self.site.config[ 'dojo?version'] or '11' page_class.theme = getattr(custom_class, 'theme', None) or self.site.config['dojo?theme'] or 'tundra' page_class.gnrjsversion = getattr(custom_class, 'gnrjsversion', None) or self.site.config[ 'gnrjs?version'] or '11' page_class.maintable = getattr(custom_class, 'maintable', None) page_class.recordLock = getattr(custom_class, 'recordLock', None) page_class.user_polling = int( getattr(custom_class, 'user_polling', None) or self.site.config['polling?user'] or 3) page_class.auto_polling = int( getattr(custom_class, 'auto_polling', None) or self.site.config['polling?auto'] or 30) if hasattr(custom_class,'polling_enabled'): page_class.polling_enabled = getattr(custom_class, 'polling_enabled') page_class.eagers = getattr(custom_class, 'eagers', {}) page_class.css_requires = [] page_class.js_requires = splitAndStrip(getattr(custom_class, 'js_requires', ''), ',') page_class.pageOptions = getattr(custom_class, 'pageOptions', {}) page_class.auth_tags = getattr(custom_class, 'auth_tags', '') page_class.resourceDirs = self.page_class_resourceDirs(page_class, module_path, pkg=mainPkg) self.page_pyrequires_mixin(page_class, py_requires) classMixin(page_class, custom_class, only_callables=False) page_class.css_requires.extend([x for x in splitAndStrip(getattr(custom_class, 'css_requires', ''), ',') if x]) page_class.tpldirectories = page_class.resourceDirs + [ self.gnr_static_handler.path(page_class.gnrjsversion, 'tpl')] page_class._packageId = mainPkg self.page_class_plugin_mixin(page_class, plugin_webpage_classes) self.page_class_custom_mixin(page_class, path, pkg=mainPkg) self.page_factories[module_path] = page_class return page_class
def decodeOneDate(datestr, workdate=None, months=None, days=None, quarters=None, locale=None, isEndPeriod=False): """Parse a string representing a date or a period. Return ``datetime.date`` or ``tuple(year,month)`` or ``None`` :param datestr: the string to be interpreted :param workdate: the :ref:`workdate` :param months: names of months according to locale (just for caching) :param days: names of weekdays according to locale (just for caching) :param quarters: names of quarters according to locale (just for caching) :param locale: the current locale (e.g: en, en_us, it) :param isEndPeriod: if the string represents a period, return the end date (default return the start date) Special keywords like ``today`` or the name of a month can be translated in all languages and support synonimous. (e.g: this month; e.g: month) The input string can be: * a year: e.g. 2007 or 07 * today, yesterday, tomorrow (can be translated in all languages) * you can specify a number of days to add to today: e.g. 'today + 3' or 'today - 15' * this week, next week, last week (can be translated in all languages) * this month, next month, last month (can be translated in all languages ) * can be specified a number of months to add to current month: e.g. 'this month + 3' or 'this month - 24' * the name of a quarter: e.g. Q1 or 1st quarter * the name of a month: e.g. april or apr * can be specified a year after the month: e.g. apr 07 or april 2007 * returns a tuple (year, month): if year is not specified in datestr, year is returned None * the name of a weekday: e.g. monday or mon * the date returned is the date of the given weekday in this week (relative to workdate) * an iso date: e.g. 2008-04-28 * a date formatted according to locale (see babel doc): e.g. 4 28, 2008 (en_us) or 28-4-08 (it) various separators are admitted: 28-4-08, 28/4/08, 28 4 08""" def addToDay(datestr, date): if '+' in datestr: days = int(datestr.split('+')[1].strip()) return date + datetime.timedelta(days) if '-' in datestr: days = int(datestr.split('-')[1].strip()) return date - datetime.timedelta(days) return date def addToMonth(datestr, date, addmonth=0):#l'errore è nel chiamate che passa addmonth sbagliato delta=0 if '+' in datestr: delta = int(datestr.split('+')[1].strip()) if '-' in datestr: delta = -int(datestr.split('-')[1].strip()) month = date.month + addmonth+ delta year = date.year while month <= 0: month = month + 12 year = year - 1 while month > 12: month = month - 12 year = year + 1 return datetime.date(year, month, 1) datestr = datestr or '' datestr = datestr.strip() if datestr: months = months or gnrlocale.getMonthNames(locale) def_months = gnrlocale.getMonthNames(DEFAULT_LOCALE) days = days or gnrlocale.getDayNames(locale) def_days = gnrlocale.getDayNames(DEFAULT_LOCALE) quarters = quarters or gnrlocale.getQuarterNames(locale) def_quarters = gnrlocale.getQuarterNames(DEFAULT_LOCALE) dateStart = None dateEnd = None workdate = workdate or datetime.date.today() if datestr.isdigit() and len(datestr) in (2, 4): # a full year year = yearDecode(datestr) dateStart = datetime.date(year, 1, 1) if isEndPeriod: dateEnd = datetime.date(year, 12, 31) elif checkDateKeywords('today', datestr, locale): # today dateStart = addToDay(datestr, workdate) elif checkDateKeywords('yesterday', datestr, locale): # yesterday dateStart = addToDay(datestr, workdate - datetime.timedelta(1)) elif checkDateKeywords('tomorrow', datestr, locale): # tomorrow dateStart = addToDay(datestr, workdate + datetime.timedelta(1)) elif checkDateKeywords(('this week', 'next week', 'last week'), datestr, locale): # relative week j = workdate.weekday() dateStart = workdate - datetime.timedelta(j) if checkDateKeywords('last week', datestr, locale): dateStart = dateStart - datetime.timedelta(7) elif checkDateKeywords('next week', datestr, locale): dateStart = dateStart + datetime.timedelta(7) if '+' in datestr: dateStart = dateStart + datetime.timedelta(7*int(datestr.split('+')[1])) if '-' in datestr: dateStart = dateStart - datetime.timedelta(7*int(datestr.split('-')[1])) if isEndPeriod: dateEnd = dateStart + datetime.timedelta(6) elif checkDateKeywords(('this month', 'next month', 'last month'), datestr, locale): # relative month if checkDateKeywords('last month', datestr, locale): dateStart = addToMonth(datestr, workdate, -1) elif checkDateKeywords('next month', datestr, locale): dateStart = addToMonth(datestr, workdate, 1) else: dateStart = addToMonth(datestr, workdate) if isEndPeriod: dateEnd = monthEnd(date=dateStart) elif anyWordIn(quarters.keys(), datestr): # quarter qt, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) qt = quarters[datestr] dateStart = (year, qt * 3 - 2) if isEndPeriod: dateEnd = (year, qt * 3) elif anyWordIn(def_quarters.keys(), datestr): # quarter qt, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) qt = def_quarters[datestr] dateStart = (year, qt * 3 - 2) if isEndPeriod: dateEnd = (year, qt * 3) elif anyWordIn(months.keys(), datestr): # month name month, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) month = months[month] dateStart = (year, month) elif anyWordIn(def_months.keys(), datestr): # month name month, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) month = def_months[month] dateStart = (year, month) elif datestr in days: # weekday name dateStart = workdate + datetime.timedelta(days[datestr] - workdate.weekday()) elif datestr in def_days: # weekday name dateStart = workdate + datetime.timedelta(def_days[datestr] - workdate.weekday()) elif re.match('\d{4}-\d{2}-\d{2}', datestr): # ISO date date_items = [int(el) for el in wordSplit(datestr)[0:3]] dateStart = datetime.date(*[int(el) for el in wordSplit(datestr)[0:3]]) else: # a date in local format dateStart = gnrlocale.parselocal(datestr, datetime.date, locale) if isEndPeriod and dateEnd: return dateEnd else: return dateStart
def setTagChildren(self, record_data, old_record_data=None): """add??? :param record_data: add??? :param old_record_data: add???. Default value is ``None`` :returns: add??? """ tablename = record_data['tablename'] parentTag = record_data['tag'] parentDescription = record_data['description'] oldChildren = {} if old_record_data: #updating parentTag_old = old_record_data['tag'] parentDescription_old = old_record_data['description'] if parentTag_old != parentTag: #updating if change parentTag def cb_tag(row): row['tag'] = row['tag'].replace('%s_' % parentTag_old, '%s_' % parentTag) row['maintag'] = parentTag self.batchUpdate( cb_tag, where='$maintag =:p_tag AND tablename=:t_name', p_tag=parentTag_old, t_name=tablename) if old_record_data and old_record_data['values']: #updating if change change values for item in splitAndStrip(old_record_data['values'], ','): tag, description = splitAndStrip('%s:%s' % (item, item), ':', n=2, fixed=2) oldChildren['%s_%s' % (parentTag, tag)] = description for item in splitAndStrip(record_data['values'], ','): tag, description = splitAndStrip('%s:%s' % (item, item), ':', n=2, fixed=2) fulltag = '%s_%s' % (parentTag, tag) if fulltag in oldChildren: if description != oldChildren[fulltag]: def cb_desc(row): row['description'] = description self.batchUpdate(cb_desc, where='$tag=:c_tag', c_tag=fulltag) oldChildren.pop(fulltag) else: self.insert( Bag( dict(tablename=tablename, tag=fulltag, description=description, maintag=parentTag, subtag=tag))) tagsToDelete = oldChildren.keys() if tagsToDelete: self.deleteSelection('tag', tagsToDelete, condition_op='IN')
def remote_getFormTags(self, pane, pkey=None, selectedRowIdx=None, call_mode=None, selectionName=None, queryValues=None, table=None, **kwargs): taglinktbl = self.db.table('%s.recordtag_link' % self.package.name) table = table or self.maintable def lblGetter (fulltag, label): return label if call_mode == 'form': tagbag = taglinktbl.getTagLinksBag(self.maintable, pkey) pane.data('.tagbag', tagbag) elif call_mode == 'list' and selectionName: pkeys = self.getUserSelection(table=table, selectionName=selectionName, selectedRowidx=selectedRowIdx).output('pkeylist') countDict = taglinktbl.getCountLinkDict(table, pkeys) def lblGetter (fulltag, label): if countDict.get(fulltag): return "%s(%i)" % (label, countDict.get(fulltag)['howmany']) return label recordtagtbl = self.db.table('%s.recordtag' % self.package.name) rows = recordtagtbl.query(where='$tablename =:tbl AND $maintag IS NULL', tbl=table, order_by='$values desc,$tag').fetch() externalFrame = pane.div(_class='tag_frame bgcolor_medium', datapath='.tagbag', padding='10px') tag_table = externalFrame.div(style='display:table;width:100%') for j, r in enumerate(rows): values = r['values'] tag = r['tag'] description = r['description'] label_width = '%fem' % ((len(description) * 0.3) + 2) buttons = [] max_width = 3 if values: for val in values.split(','): subtag, label = splitAndStrip('%s:%s' % (val, val), ':', n=2, fixed=2) fulltag = '%s_%s' % (tag, subtag) label = lblGetter(fulltag, label) buttons.append( dict(value='^.%s' % subtag, _class='dijitButtonNode tag_button tag_value', label=label, fulltag=fulltag)) for b in buttons: if len(b['label']) > max_width: max_width = len(b['label']) max_width = '%fem' % ((max_width * .5) + 2) else: label = lblGetter(tag, '!!Yes') buttons.append( dict(value='^.true', _class='dijitButtonNode tag_button tag_true', label=label, fulltag=tag)) oddOrEven = 'even' colorRow = 'bgcolor_bright' if j % 2: oddOrEven = 'odd' colorRow = 'bgcolor_brightest' tag_row = tag_table.div(style='display:table-row', height='5px') #no dimensioni riga solo padding dimensioni ai contenuti delle celle tag_row = tag_table.div(style='display:table-row', _class='tag_line tag_%s' % (oddOrEven), datapath='.%s' % tag) #no dimensioni riga solo padding dimensioni ai contenuti delle celle if call_mode == 'form': label_col = tag_row.div(description, style='display:table-cell', width=label_width, _class='tag_left_col tag_label_col bgcolor_darkest color_brightest') else: cb_col = tag_row.div(style='display:table-cell', _class='tag_left_col bgcolor_darkest color_brightest', padding_left='10px', width='30px') cb_col.checkbox(value='^.?enabled', validate_onAccept="""if(!value){ var line = GET #; line.walk(function(node){if(node.getValue()){node.setValue(null);}}); SET .?selectedTag = null; }else if(userChange){ SET .?enabled = false; }""") label_col = tag_row.div(description, style='display:table-cell', width=label_width, _class='bgcolor_darkest color_brightest tag_label_col', padding_left='10px') no_td = tag_row.div(style='display:table-cell', _class=colorRow, width='4em').div( _class='dijitButtonNode tag_button tag_false') if call_mode == 'helper' and queryValues: if tag in queryValues['tagged_not']: no_td.data('.false', True) no_td.data('.?enabled', True) no_td.data('.?selectedTag', '!%s' % tag) no_td.radiobutton(value='^.false', label='!!No', group=tag, connect_onclick='SET .?enabled= true; SET .?selectedTag="!%s";' % tag) value_col = tag_row.div(style='display:table-cell', _class='tag_value_col %s' % colorRow) for btn in buttons: value_td = value_col.div(_class=btn['_class'], width=max_width) if call_mode == 'helper' and queryValues: if btn['fulltag'] in queryValues['tagged']: value_td.data(btn['value'][1:], True) value_td.data('.?enabled', True) value_td.data('.?selectedTag', btn['fulltag']) value_td.radiobutton(value=btn['value'], label=btn['label'], group=tag, connect_onclick='SET .?enabled= true; SET .?selectedTag="%s";' % btn['fulltag'])
def decodeOneDate(datestr, workdate=None, months=None, days=None, quarters=None, locale=None, isEndPeriod=False): """Parse a string representing a date or a period. Return ``datetime.date`` or ``tuple(year,month)`` or ``None`` :param datestr: the string to be interpreted :param workdate: the :ref:`workdate` :param months: names of months according to locale (just for caching) :param days: names of weekdays according to locale (just for caching) :param quarters: names of quarters according to locale (just for caching) :param locale: the current locale (e.g: en, en_us, it) :param isEndPeriod: if the string represents a period, return the end date (default return the start date) Special keywords like ``today`` or the name of a month can be translated in all languages and support synonimous. (e.g: this month; e.g: month) The input string can be: * a year: e.g. 2007 or 07 * today, yesterday, tomorrow (can be translated in all languages) * you can specify a number of days to add to today: e.g. 'today + 3' or 'today - 15' * this week, next week, last week (can be translated in all languages) * this month, next month, last month (can be translated in all languages ) * can be specified a number of months to add to current month: e.g. 'this month + 3' or 'this month - 24' * the name of a quarter: e.g. Q1 or 1st quarter * the name of a month: e.g. april or apr * can be specified a year after the month: e.g. apr 07 or april 2007 * returns a tuple (year, month): if year is not specified in datestr, year is returned None * the name of a weekday: e.g. monday or mon * the date returned is the date of the given weekday in this week (relative to workdate) * an iso date: e.g. 2008-04-28 * a date formatted according to locale (see babel doc): e.g. 4 28, 2008 (en_us) or 28-4-08 (it) various separators are admitted: 28-4-08, 28/4/08, 28 4 08""" def addToDay(datestr, date): if '+' in datestr: days = int(datestr.split('+')[1].strip()) return date + datetime.timedelta(days) if '-' in datestr: days = int(datestr.split('-')[1].strip()) return date - datetime.timedelta(days) return date def addToMonth(datestr, date, addmonth=0):#l'errore è nel chiamate che passa addmonth sbagliato delta=0 if '+' in datestr: delta = int(datestr.split('+')[1].strip()) if '-' in datestr: delta = -int(datestr.split('-')[1].strip()) month = date.month + addmonth+ delta year = date.year while month <= 0: month = month + 12 year = year - 1 while month > 12: month = month - 12 year = year + 1 return datetime.date(year, month, 1) datestr = datestr or '' datestr = datestr.strip() if datestr: months = months or gnrlocale.getMonthNames(locale) def_months = gnrlocale.getMonthNames(DEFAULT_LOCALE) days = days or gnrlocale.getDayNames(locale) def_days = gnrlocale.getDayNames(DEFAULT_LOCALE) quarters = quarters or gnrlocale.getQuarterNames(locale) def_quarters = gnrlocale.getQuarterNames(DEFAULT_LOCALE) dateStart = None dateEnd = None workdate = workdate or datetime.date.today() if datestr.isdigit() and len(datestr) in (2, 4): # a full year year = yearDecode(datestr) dateStart = datetime.date(year, 1, 1) if isEndPeriod: dateEnd = datetime.date(year, 12, 31) elif checkDateKeywords('today', datestr, locale): # today dateStart = addToDay(datestr, workdate) elif checkDateKeywords('yesterday', datestr, locale): # yesterday dateStart = addToDay(datestr, workdate - datetime.timedelta(1)) elif checkDateKeywords('tomorrow', datestr, locale): # tomorrow dateStart = addToDay(datestr, workdate + datetime.timedelta(1)) elif checkDateKeywords(('this week', 'next week', 'last week'), datestr, locale): # relative week j = workdate.weekday() dateStart = workdate - datetime.timedelta(j) if checkDateKeywords('last week', datestr, locale): dateStart = dateStart - datetime.timedelta(7) elif checkDateKeywords('next week', datestr, locale): dateStart = dateStart + datetime.timedelta(7) if '+' in datestr: dateStart = dateStart + datetime.timedelta(7*int(datestr.split('+')[1])) if '-' in datestr: dateStart = dateStart - datetime.timedelta(7*int(datestr.split('-')[1])) if isEndPeriod: dateEnd = dateStart + datetime.timedelta(6) elif checkDateKeywords(('this month', 'next month', 'last month'), datestr, locale): # relative month if checkDateKeywords('last month', datestr, locale): dateStart = addToMonth(datestr, workdate, -1) elif checkDateKeywords('next month', datestr, locale): dateStart = addToMonth(datestr, workdate, 1) else: dateStart = addToMonth(datestr, workdate) if isEndPeriod: dateEnd = monthEnd(date=dateStart) elif anyWordIn(quarters.keys(), datestr): # quarter qt, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) qt = quarters[qt] dateStart = (year, qt * 3 - 2) if isEndPeriod: dateEnd = (year, qt * 3) elif anyWordIn(def_quarters.keys(), datestr): # quarter qt, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) qt = def_quarters[datestr] dateStart = (year, qt * 3 - 2) if isEndPeriod: dateEnd = (year, qt * 3) elif anyWordIn(months.keys(), datestr): # month name month, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) month = months[month] dateStart = (year, month) elif anyWordIn(def_months.keys(), datestr): # month name month, year = splitAndStrip(datestr, sep=' ', n=1, fixed=2) year = yearDecode(year) month = def_months[month] dateStart = (year, month) elif datestr in days: # weekday name dateStart = workdate + datetime.timedelta(days[datestr] - workdate.weekday()) elif datestr in def_days: # weekday name dateStart = workdate + datetime.timedelta(def_days[datestr] - workdate.weekday()) elif re.match('\d{4}-\d{2}-\d{2}', datestr): # ISO date date_items = [int(el) for el in wordSplit(datestr)[0:3]] dateStart = datetime.date(*[int(el) for el in wordSplit(datestr)[0:3]]) else: # a date in local format dateStart = gnrlocale.parselocal(datestr, datetime.date, locale) if isEndPeriod and dateEnd: return dateEnd else: return dateStart
def remote_getFormTags( self, pane, pkey=None, selectedRowIdx=None, call_mode=None, selectionName=None, queryValues=None, table=None, **kwargs ): taglinktbl = self.db.table("%s.recordtag_link" % self.package.name) table = table or self.maintable def lblGetter(fulltag, label): return label if call_mode == "form": tagbag = taglinktbl.getTagLinksBag(self.maintable, pkey) pane.data(".tagbag", tagbag) elif call_mode == "list" and selectionName: pkeys = self.getUserSelection( table=table, selectionName=selectionName, selectedRowidx=selectedRowIdx ).output("pkeylist") countDict = taglinktbl.getCountLinkDict(table, pkeys) def lblGetter(fulltag, label): if countDict.get(fulltag): return "%s(%i)" % (label, countDict.get(fulltag)["howmany"]) return label recordtagtbl = self.db.table("%s.recordtag" % self.package.name) rows = recordtagtbl.query( where="$tablename =:tbl AND $maintag IS NULL", tbl=table, order_by="$values desc,$tag" ).fetch() externalFrame = pane.div(_class="tag_frame bgcolor_medium", datapath=".tagbag", padding="10px") tag_table = externalFrame.div(style="display:table;width:100%") for j, r in enumerate(rows): values = r["values"] tag = r["tag"] description = r["description"] label_width = "%fem" % ((len(description) * 0.3) + 2) buttons = [] max_width = 3 if values: for val in values.split(","): subtag, label = splitAndStrip("%s:%s" % (val, val), ":", n=2, fixed=2) fulltag = "%s_%s" % (tag, subtag) label = lblGetter(fulltag, label) buttons.append( dict( value="^.%s" % subtag, _class="dijitButtonNode tag_button tag_value", label=label, fulltag=fulltag, ) ) for b in buttons: if len(b["label"]) > max_width: max_width = len(b["label"]) max_width = "%fem" % ((max_width * 0.5) + 2) else: label = lblGetter(tag, "!!Yes") buttons.append( dict(value="^.true", _class="dijitButtonNode tag_button tag_true", label=label, fulltag=tag) ) oddOrEven = "even" colorRow = "bgcolor_bright" if j % 2: oddOrEven = "odd" colorRow = "bgcolor_brightest" tag_row = tag_table.div( style="display:table-row", height="5px" ) # no dimensioni riga solo padding dimensioni ai contenuti delle celle tag_row = tag_table.div( style="display:table-row", _class="tag_line tag_%s" % (oddOrEven), datapath=".%s" % tag ) # no dimensioni riga solo padding dimensioni ai contenuti delle celle if call_mode == "form": label_col = tag_row.div( description, style="display:table-cell", width=label_width, _class="tag_left_col tag_label_col bgcolor_darkest color_brightest", ) else: cb_col = tag_row.div( style="display:table-cell", _class="tag_left_col bgcolor_darkest color_brightest", padding_left="10px", width="30px", ) cb_col.checkbox( value="^.?enabled", validate_onAccept="""if(!value){ var line = GET #; line.walk(function(node){if(node.getValue()){node.setValue(null);}}); SET .?selectedTag = null; }else if(userChange){ SET .?enabled = false; }""", ) label_col = tag_row.div( description, style="display:table-cell", width=label_width, _class="bgcolor_darkest color_brightest tag_label_col", padding_left="10px", ) no_td = tag_row.div(style="display:table-cell", _class=colorRow, width="4em").div( _class="dijitButtonNode tag_button tag_false" ) if call_mode == "helper" and queryValues: if tag in queryValues["tagged_not"]: no_td.data(".false", True) no_td.data(".?enabled", True) no_td.data(".?selectedTag", "!%s" % tag) no_td.radiobutton( value="^.false", label="!!No", group=tag, connect_onclick='SET .?enabled= true; SET .?selectedTag="!%s";' % tag, ) value_col = tag_row.div(style="display:table-cell", _class="tag_value_col %s" % colorRow) for btn in buttons: value_td = value_col.div(_class=btn["_class"], width=max_width) if call_mode == "helper" and queryValues: if btn["fulltag"] in queryValues["tagged"]: value_td.data(btn["value"][1:], True) value_td.data(".?enabled", True) value_td.data(".?selectedTag", btn["fulltag"]) value_td.radiobutton( value=btn["value"], label=btn["label"], group=tag, connect_onclick='SET .?enabled= true; SET .?selectedTag="%s";' % btn["fulltag"], )