Exemplo n.º 1
0
    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
Exemplo n.º 2
0
 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
Exemplo n.º 3
0
 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
Exemplo n.º 4
0
 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
Exemplo n.º 5
0
	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
Exemplo n.º 6
0
    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)
Exemplo n.º 7
0
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
Exemplo n.º 8
0
 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
Exemplo n.º 9
0
 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()
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
 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)
Exemplo n.º 13
0
 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)
Exemplo n.º 14
0
 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
Exemplo n.º 15
0
 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
Exemplo n.º 16
0
    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)
Exemplo n.º 17
0
 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()
Exemplo n.º 18
0
    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)
Exemplo n.º 19
0
 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
Exemplo n.º 20
0
 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)
Exemplo n.º 21
0
    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):]
Exemplo n.º 22
0
 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
Exemplo n.º 23
0
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
Exemplo n.º 24
0
    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)
Exemplo n.º 25
0
    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)
Exemplo n.º 26
0
 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}
Exemplo n.º 27
0
    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()
Exemplo n.º 28
0
    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
Exemplo n.º 29
0
 async def sqlExe(self, sql, ns):
     ret = []
     await self.execute(sql,
                        ns,
                        callback=lambda x: ret.append(DictObject(**x)))
     return ret
Exemplo n.º 30
0
 def handler(self, rec):
     obj = DictObject(**rec)
     self.ns[self.name].append(obj)