def _99field(self, row): _status = 0 _tag = 1 _label = 2 _fmt = 3 if len(row) == 7: _label = 4 _fmt = 5 tag = str(row[_tag].value) fmtstr = nl2crnl(row[_fmt].value) if fmtstr.startswith('copy'): fmtstr = '' if fmtstr.startswith('Empty'): fmtstr = '' if ' ' in tag: tag = tag.split(' ')[0] if tag[-1] != 'a' and ' ' in fmtstr: fmtstr = fmtstr.split(' ')[0] name = 'f_' + str(tag) object = '99field' if self.curobj.name == 'b3' or self.curobj.name == 'b5': object = '999field' field = DictObject(object=object, name=name, kwargs=DictObject(status=row[_status].value, tag=tag, label=row[_label].value, subnames=[], formatstr=fmtstr), children=[]) self.curobj.children.append(field) self.lastobj = field
def segment(self, row): seg = DictObject(object='segment', name=row[1].value, kwargs=DictObject(status=row[2].value, repeat_flg=row[3].value), children=[]) self.curobj.children.append(seg) self.lifo.append(self.curobj) self.curobj = seg
def defaultCurObj(self): if self.curobj is self: msgdic = DictObject(name='b4', object="block", children=[], kwargs=DictObject(tag='4'), schildren=[]) self.children.append(msgdic) self.curobj = msgdic self.lastobj = msgdic
def block(self, row): block = DictObject( object='block', name=row[1].value, kwargs=DictObject( tag=str(row[2].value), formatstr='' if row[3].value is None else row[3].value), children=[]) self.curobj.children.append(block) self.lifo.append(self.curobj) self.curobj = block
def store(self,path,obj): o = self.cache.get(path,None) if o is not None: try: del o.cached_obj except: pass o = DictObject() o.cached_obj = obj o.mtime = os.path.getmtime(path) self.cache[path] = o
def _999field(self, row): field = DictObject(object='999field', name='f_' + str(row[2].value), kwargs=DictObject(status=row[1].value, tag=str(row[2].value), label=row[3].value, subnames=[], formatstr=nl2crnl(row[4].value)), children=[]) if field.kwargs.formatstr.startswith('Empty'): field.formatstr = '' self.curobj.children.append(field)
def tag_xor(tag, opts, pack_name=""): fmtdic = {} method = tag_methods.get(tag, None) if method is None: raise Exception("tag(%s) has not methods" % tag) keys = [i for i in opts if i <= 'Z' and i >= 'A'] # print(opts,'-----keys=',keys,'----') keys = [i if i in method.keys() else '' for i in keys] # print('-----keys=',keys,'----') [fmtdic.update({i: method.get(i)}) for i in keys] d = DictObject(name="party", object="xor", kwargs=DictObject(name="party_n", fmtdic=fmtdic)) return d
def block(self, row): ns = [] if row[4].value is None else row[4].value.split(',') block = DictObject( object='block', name=row[1].value, kwargs=DictObject( tag=str(row[2].value), formatstr='' if row[3].value is None else row[3].value, subnames=ns), children=[], schildren=[]) self.curobj.children.append(block) self.lifo.append(self.curobj) self.curobj = block
def __init__(self, prefix: str, directory: PathLike, *, name: Optional[str] = None, expect_handler: Optional[_ExpectHandler] = None, chunk_size: int = 256 * 1024, show_index: bool = False, follow_symlinks: bool = False, append_version: bool = False, indexes: list = [], processors: dict = {}) -> None: AppLogger.__init__(self) StaticResource.__init__(self, prefix, directory, name=name, expect_handler=expect_handler, chunk_size=chunk_size, show_index=show_index, follow_symlinks=follow_symlinks, append_version=append_version) Url2File.__init__(self, directory, prefix, indexes, inherit=True) gr = self._routes.get('GET') self._routes.update({'POST': gr}) self._routes.update({'PUT': gr}) self._routes.update({'OPTIONS': gr}) self._routes.update({'DELETE': gr}) self._routes.update({'TRACE': gr}) self.y_processors = processors self.y_prefix = prefix self.y_directory = directory self.y_indexes = indexes self.y_env = DictObject()
def keyMapping(dic, mappingtab, keepmiss=True): ret = {} keys = [k for k in dic.keys()] if not keepmiss: keys = [k for k in dic.keys() if k in mappingtab.keys()] [ret.update({mappingtab.get(k, k): dic[k]}) for k in keys] return DictObject(**ret)
def valueMapping(dic, mappingtab): """ mappingtab format: { "field1":{ "a":"1", "b":"2", "__default__":"5" }, "field2":{ "a":"3", "b":"4" } } field1,field2 is in dic.keys() """ ret = {} for k in dic.keys(): mt = mappingtab.get(k, None) if mt is None: ret[k] = dic[k] else: dv = mt.get('__default__', dic[k]) v = mt.get(dic[k], dv) ret[k] = v return DictObject(**ret)
async def datahandle(self, request): path = self.resource.extract_path(request) g = ServerEnv() ns = DictObject() ns.update(g) ns.update(self.resource.env) ns.request = request ns.ref_real_path = self.path te = g.tmpl_engine self.content = te.render(path, **ns)
async def datahandle(self, request): dict_data = {} config = getConfig() with codecs.open(self.path, 'r', config.website.coding) as f: b = f.read() dict_data = json.loads(b) ns = DictObject() g = ServerEnv() ns.update(g) ns.update(self.resource.env) ns.update(self.resource.getGetArgs(request)) act = ns.get('action', 'getdata') action = self.actions.get(act) self.content = action(dict_data, ns, request)
def segment(self, row): name = self.getSegmentName() status = 'M' if 'Mandatory' in row[0].value else 'O' repeat_flg = False if row[0].value == '----->' or 'Repetitive' in row[0].value: repeat_flg = True seg = DictObject( object='segment', name=name, kwargs=DictObject(status=status, repeat_flg=repeat_flg), children=[], schildren=[], ) self.curobj.children.append(seg) self.curobj.schildren.append(seg) self.lifo.append(self.curobj) self.curobj = seg self.lastobj = seg
async def resultFields(self, desc, NS): NS.update(rows=1, page=1) r = await self.pagingdata(desc, NS) ret = [ DictObject(**{ 'name': i[0], 'type': i[1] }) for i in self.cur.description ] return ret
def _99field(self, row): field = DictObject( object='99field', name='f_' + str(row[2].value), kwargs=DictObject( status=row[1].value, tag=str(row[2].value), label=row[3].value, subnames=[], formatstr=nl2crnl( '' if row[4].value is None else row[4].value)), children=[]) if field.kwargs.formatstr.startswith('Empty'): field.kwargs.formatstr = '' #if len(field.kwargs.tag)==3 and field.kwargs.tag[2] == 'a': # d = tag_xor(field.kwargs.tag,field.kwargs.formatstr) # field.children.append(d) v = [c.value for c in row] self.curobj.children.append(field)
def __init__(self, paths: list, indexes: list = [], accessController=None): StaticHandler.__init__(self, paths=paths, url_prefix='') Url2File.__init__(self, paths, indexes, inherit=True) super(BaseResource, self).__init__(paths=paths, url_prefix='') self.processors = {} self.indexes = indexes self.app = None self.access_controller = accessController if accessController is not None: self.access_controller.resource = self self.env = DictObject()
def __init__(self, jsonholder, keytype='ansi', NS=None): self.__jsonholder__ = jsonholder self.NS = NS jhtype = type(jsonholder) if jhtype == type("") or jhtype == type(u''): f = open(jsonholder, 'r') else: f = jsonholder try: a = json.load(f) except Exception as e: print("exception:", self.__jsonholder__, e) raise e finally: if type(jsonholder) == type(""): f.close() if self.NS is not None: ac = ArgsConvert('$[', ']$') a = ac.convert(a, self.NS) DictObject.__init__(self, **a)
def build(self, msgtype, direction='I'): dic = self.msgdic.get(msgtype + direction, None) if dic is None: xlsx = SwiftShortXlsx(msgtype, direction=direction) dic = xlsx.json() self.msgdic[msgtype + direction] = dic msgdic = DictObject(name='swiftmsg', object="message", children=dic['Specification']) swiftmsg = self.parse(msgdic, root=None, parent=None) swiftmsg.CheckingRule = dic['CheckingRule'] swiftmsg.fieldMapping = dic['FieldMapping'] swiftmsg.matchingRule = dic['MatchingRule'] return swiftmsg
def getReceivedData(self, transferBytes, addr): crypted, zipped, sender, receiver, body = transferBytes.split('|+|') if receiver != self.myname: return None self.setPeerAddr(sender, addr) if crypted == '0': d = json.loads(body) d['sender'] = sender d['receiver'] = receiver d['sender_addr'] = addr return DictObject(**d) cryptedkey, sign, cryptedText = body.split('|@|') key = self.rsa.decode(self.private_key, cryptedkey) text = rc4.decode(cryptText, key) spubk = self.rsa.publickeyFromText(self.getPeerPublickey(sender)) r = self.rsa.check_sign(spubk, text, sign) if not r: return None d = json.loads(text) d['sender'] = sender d['receiver'] = receiver d['sender_addr'] = addr return DictObject(**d)
def unpack(self): print('unpack 99field', self.tag, self.name) def optionalReturnText(txt): if self.isOptional(): return txt raise Exception('unpack error,tag=%s,startword=%s,txt=%s' \ % (self.tag, self.startword, txt)) text = self.textData if not self.xor_flg and not text.startswith(self.startword): print('unpack 99field', self.tag, 'failed 1') return optionalReturnText(text) if self.xor_flg: if not text.startswith(self.startword[:3]): print('unpack 99field', self.tag, 'failed 2') return optionalReturnText(text) if text[4] != ':': print('unpack 99field', self.tag, 'failed 3') return optionalReturnText(text) self.children[0].name = text[3] self.textData = self.textData[len(self.startword):] txt = super(SwiftXXField, self).unpack() if txt is None: self.innerData = DictObject() print('unpack 99field', self.tag, 'failed 4') return optionalReturnText(self.textData) if not txt.startswith(self.endword): print('unpack 99field', self.tag, 'failed 5') self.innerData = DictObject() return optionalReturnText(text) print('unpack 99field', self.tag, 'finished') return txt[len(self.endword):]
def json(self): configs = [] for name in self.wb.sheetnames: msgdic = DictObject(name=name, object="message", children=[]) self.lifo = [] self.curobj = msgdic ws = self.wb[name] print('sheet=', name) self.readBlocks(ws) if len(self.lifo) > 0: print(self.lifo, 'not finished') raise Exception('stack not empty') configs.append(msgdic) ws = self.wb[name] return configs
def pack(data): d = DictObject(data) io = d.b2.direction msgtype = d.b2.msgtype asm = AssemblyLine() msg = asm.build(msgtype, io) try: msg.innerData = data if needCheck: checker = SwiftChecker() checker.check(msg) msg.pack() return msg.textData except Exception as e: print(e) return None
async def path_call(self, request, path): path1 = request.path[len(self.config_opts['leading']):] args = [] if len(path1) > 0: if path1[0] == '/': path1 = path1[1:] args = path1.split('/') rfname = self.config_opts['registerfunction'] ns = DictObject(**self.run_ns) rf = RegisterFunction() f = rf.get(rfname) self.run_ns['request'] = request globals().update(self.run_ns) if inspect.iscoroutinefunction(f): return await f(*args, **self.run_ns) return f(*args)
def RP(self, tblname, filters=None, NS={}): @runSQLIterator def totalCount(dbname, data, filterString): sqldesc = { "sql_string": """select * from %s where 1=1 %s""" % (tblname, filterString), "count": True, "default": { 'rows': self.rows } } return sqldesc @runSQLIterator def pagingdata(dbname, data, filterString): sqldesc = { "sql_string": """select * from %s where 1=1 %s""" % (tblname, filterString), "paging": { "rowsname": "rows", "pagename": "page" }, "default": { 'rows': self.rows } } return sqldesc if not NS.get('sort', False): fields = getTableFields(self.dbname, tblname) NS['sort'] = fields[0]['name'] fstr = "" if filters is not None: fstr = ' and ' dbf = DBFilter(filters) fstr = fstr + dbf.genFilterString() else: fstr = self.defaultFilter(tblname, NS) rtv_cnt = [i for i in totalCount(self.dbname, NS, fstr)] total = rtv_cnt[0].rcnt d = [r for r in pagingdata(self.dbname, NS, fstr)] ret = {'total': total, 'rows': d} return DictObject(**ret)
def readRecords(self, sheet): i = 1 recs = [] name = sheet.name fields = self.getFieldNames(sheet) tc = TypeConvert() while (i < sheet.nrows): j = 0 rec = {} while (j < sheet.ncols): a = sheet.cell(i, j).value k = fields[j][0] v = tc.conv(fields[j][1], a) rec[k] = v j += 1 o = DictObject(**rec) recs.append(o) i += 1 return {name: recs}
def execute(self, sql, value, callback, *args, **kwargs): cur = self.cursor() self.runVarSQL(cur, sql, value) if callback is not None: fields = [i[0].lower() for i in cur.description] rec = cur.fetchone() while rec is not None: dic = {} for i in range(len(fields)): dic.update({fields[i]: rec[i]}) dic = uDict(dic, coding='utf8') obj = DictObject(**dic) callback(obj, *args, **kwargs) rec = cur.fetchone() r = cur.fetchone() while r: callback(r) r = cur.fetchone() cur.close()
async def execute(self, sql, value, callback, **kwargs): sqltype = self.getSqlType(sql) cur = self.cursor() await self.runVarSQL(cur, sql, value) if sqltype == 'qry' and callback is not None: fields = [i[0].lower() for i in cur.description] rec = None if self.async_mode: rec = await cur.fetchone() else: rec = cur.fetchone() while rec is not None: dic = {} for i in range(len(fields)): dic.update({fields[i]: db_type_2_py_type(rec[i])}) callback(DictObject(**dic), **kwargs) if self.async_mode: rec = await cur.fetchone() else: rec = cur.fetchone() if sqltype == 'dml': self.dataChanged = True
async def sqlExe(self, sql, ns): ret = [] await self.execute(sql, ns, callback=lambda x: ret.append(DictObject(**x))) return ret
def handler(self, rec): obj = DictObject(**rec) self.ns[self.name].append(obj)