def switch_sos_console(self, login_name, login_pwd): ''' switch to vm_console NUM ''' logging.info('Call switch_sos_console()') cmd = 'vm_console' self.__run_cmd(cmd) time.sleep(2) self._expect.send('\r') # active prompt self._cmd_prompt = login_name + '@' logging.info('Start SOS login ...') try: self._expect.expect('login:'******'enter login name %s' % login_name) self._expect.sendline(login_name) self._expect.expect('Password:'******'enter login password %s' % login_pwd) self._expect.sendline(login_pwd) self._expect.expect(self._cmd_prompt) time.sleep(2) except: # NOQA logging.warnning('Login SOS failed.') return False self.set_sos_username(login_name) self.set_sos_password(login_pwd) return True
async def update(self): args = list(map(self.getValue, self.__fields__)) args.append(self.getValue(self.__primary_key__)) rows = await execute(self.__update__, args) if rows != 1: logging.warnning( 'failed to update by primary key: affected rows: %s' % rows)
def add_favorite(request): if request.method == "GET": user = request.user print(user.username) goodsid = request.GET.get("goodsid", "") colorid = request.GET.get("colorid", "") sperid = request.GET.get("sperid", "") try: goods = Goods.objects.get(id=goodsid) goodcolor = GoodsColor.objects.get(id=colorid) goodspe = GoodsDetail.objects.get(id=sperid) except DatabaseError as e: logging.warnning(e) favorite = Favorite.objects.filter(user=user, goods_id=goodsid, color=goodcolor.color, spec=goodspe.specifice) if favorite: return HttpResponse( json.dumps({ "result": False, "data": "", "error": "已收藏" })) else: Favorite.objects.create(user=user, goods=goods, color=goodcolor.color, spec=goodspe.specifice) return HttpResponse( json.dumps({ "result": True, "data": "添加成功", "error": "" }))
def buynow(request): if request.method == "POST": user = request.user goodsid = request.POST.get("goodsid", "") colorid = request.POST.get("colorid", "") sperid = request.POST.get("sperid", "") amount = request.POST.get("amount", "") try: goods = Goods.objects.get(id=goodsid) goodcolor = GoodsColor.objects.get(id=colorid) goodspe = GoodsDetail.objects.get(id=sperid) except DatabaseError as e: logging.warnning(e) return HttpResponse( json.dumps({ "result": False, "data": "", "error": "异常" })) buyit = Buynow() buyit.user = user buyit.goods = goods buyit.color = goodcolor.color buyit.spec = goodspe.specifice buyit.amount = int(amount) buyit.save() return HttpResponse( json.dumps({ "result": True, "data": "添加成功", "error": "" })) elif request.method == "GET": pass
async def save(self): args = list(map(self.getValueOrDefault, self.__fields__)) args.append(self.getValueOrDefault(self.__primary_key__)) rows = await execute(self.__insert__, args) if rows != 1: logging.warnning('failed to insert record: affected rows: %s' % rows)
def __call__(self, request): kw = None if self._has_var_kw_arg or self._has_named_kw_args or self._required_kw_args: if request.method == "POST": if not request.content_type: logging.info("11111111111111111111111111111") return web.HTTPBadRequest('Missing Content-Type') ct = request.content_type.lower() if ct.startswith("application/json"): params = yield from request.json() logging.info(params) if not isinstance(params, dict): logging.info("22222222222222222222222222222") return web.HTTPBadRequest("JSON body must be object") kw = params elif ct.startswith("application/x-www-form-urlencoded" ) or ct.startswith("multipart/form-data"): params = yield from request.post() kw = dict(**params) else: logging.info("3333333333333333333333333333333333") return web.HTTPBadRequest("Unsupported Content-type: %s" % request.content_type) if request.method == "GET": qs = request.query_string if qs: kw = dict() for k, v in parse.parse_qs(qs, True).items(): kw[k] = v[0] if kw is None: kw = dict(**request.match_info) else: if not self._has_var_kw_arg and self._named_kw_args: copy = dict() for name in self._named_kw_args: if name in kw: copy[name] = kw[name] kw = copy for k, v in request.match_info.items(): if k in kw: logging.warnning( 'Duplicate arg name in named arg and kw args: %s' % k) kw[k] = v if self._has_request_arg: kw['request'] = request if self._required_kw_args: for name in self._required_kw_args: if name not in kw: logging.info("4444444444444444444444444444444444444") return web.HTTPBadRequest('Missing argument: %s' % name) logging.info("call with args: %s" % str(kw)) logging.info(str(self._func)) try: r = yield from self._func(**kw) return r except APIError as e: return dict(error=e.error, data=e.data, message=e.message)
def check_progs_inter(SSTAT,PROTOC, message,sock): # for check_progs client_tasks_id = message[PROTOC.attr.client_tasks_id] task_log_idx = message[PROTOC.attr.task_log_idx] logging.debug('Enter check_progs_inter') # check current task if(SSTAT.current_thread != None): logging.debug('current_thread : %s + %d'%(SSTAT.current_thread.client_tasks_id,SSTAT.current_thread.task_log_idx)) if ( SSTAT.current_thread.client_tasks_id == client_tasks_id and SSTAT.current_thread.task_log_idx == task_log_idx): # If the requested task is current thread task done_count = SSTAT.current_thread.get_taskdone_count() remain_count = SSTAT.current_thread.get_remain_count() reply = PROTOC.gen_check_prog_curentT_rep(done_count,remain_count) PROTOC.send_msg(sock,reply) # keeps pinging and checking until one finished. while True: data = PROTOC.recv_msg(sock) pingMsg = PROTOC.parse(data) if pingMsg[PROTOC.attr.msg_type] == PROTOC.request.ping: if(SSTAT.current_thread != None): if ( SSTAT.current_thread.client_tasks_id == client_tasks_id and SSTAT.current_thread.task_log_idx == task_log_idx): done_count = SSTAT.current_thread.get_taskdone_count() remain_count = SSTAT.current_thread.get_remain_count() reply = PROTOC.gen_check_prog_curentT_rep(done_count,remain_count) PROTOC.send_msg(sock,reply) else: # thread is changed , Though this is very unlikely. # try to find the result in the past tasks check_progs_in_past(SSTAT,PROTOC,client_tasks_id,task_log_idx,sock) logging.debug('Current thread is no longer processing the task, try to serch result in Output') break else: # current thread is ended # try to find the result in the past tasks logging.debug('Current task is just completed, try to search result in Output') check_progs_in_past(SSTAT,PROTOC,client_tasks_id,task_log_idx,sock) break elif pingMsg[PROTOC.attr.msg_type] == PROTOC.request.end: # the client side end the stream, break and end. logging.debug('Received end signal from client, break the communication') break else: # cannot recognize the message received, show an error and break,(or pass?) logging.warnning('echoS:check_progs_inter: Received message is not ping or end, abort message and quit.') break else: # Current task is not the requested task, try to find out in past tasks logging.debug('current tasks is not requested task, try check_progs_in_past ') check_progs_in_past(SSTAT,PROTOC,client_tasks_id,task_log_idx,sock) else: # try to find the result in the past tasks logging.debug('current thread is None, try check_progs_in_past') check_progs_in_past(SSTAT,PROTOC,client_tasks_id,task_log_idx,sock)
def add_cart(request): if request.method == "POST": user = request.user goodsid = request.POST.get("goodsid", "") colorid = request.POST.get("colorid", "") sperid = request.POST.get("sperid", "") amount = request.POST.get("amount", "") try: goods = Goods.objects.get(id=goodsid) goodcolor = GoodsColor.objects.get(id=colorid) goodspe = GoodsDetail.objects.get(id=sperid) except DatabaseError as e: logging.warnning(e) return HttpResponse( json.dumps({ "result": False, "data": "", "error": "异常" })) allcart = Cart.objects.all() if len(allcart) < 120: oldcart = Cart.objects.filter(user_id=user.id, goods_id=goodsid, color=goodcolor.color, spec=goodspe.specifice) if oldcart: oldcart[0].amount = oldcart[0].amount + int(amount) oldcart[0].save() else: new_cart = Cart() new_cart.user = user new_cart.goods = goods new_cart.color = goodcolor.color new_cart.spec = goodspe.specifice new_cart.price = decimal.Decimal(goods.price) new_cart.amount = int(amount) new_cart.save() cart = Cart.objects.filter(user=user, goods=goods, color=goodcolor.color, spec=goodspe.specifice) cartid = cart[0].id return HttpResponse( json.dumps({ "result": True, "data": cartid, "error": "" })) else: return HttpResponse( json.dumps({ "result": False, "data": "", "error": "购物车数量超过限制" })) elif request.method == "GET": pass
def __new__(cls,name,bases,attrs): if name == 'Model': return type.__new__(cls,name,bases,attrs) #store all subclasses info: #凡是由cls定义出来的类,那么肯定记录在cls的sublclasses表中,如果已经存在对应项,表示该类已经定义过了 #不是父类和子类的关系,而是元类和经由元类定义的类的关系 if not hasattr(cls, 'subclasses'): cls.subclasses = {} if not name in cls.subclasses: cls.subclasses[name] = name else: logging.warnning('Redifine class:%s' %name) logging.info('Scan ORMapping %s...' %name) mappings = dict() primary_key = None for k,v in attrs.iteritems(): if isinstance(v,Field): if not v.name: v.name = k logging.info('Found mapping: %s => %s' % (k, v)) #check duplicat primary key: #primary_key:固定优先查询项,如依靠id来进行查询,那么id必须是不可变且非空的,并且一个实体只能有一个id值 if v.primary_key: if primary_key: raise TypeError('Cannot define more than 1 primary key in class:%s'%name) if v.updatable: logging.warning('Note:change primary key to non-updatable') v.updatable = False if v.nullable: logging.warning('Note:change primary key to non-nullable.') v.nullable = False primary_key = v mappings[k] = v # check exist of primary key: if not primary_key: raise TypeError('Primary key not defined in class: %s' % name) for k in mappings.iterkeys(): attrs.pop(k) if not '__table__'in attrs: attrs['__table__'] = name.lower() attrs['__mappings__'] = mappings attrs['__primary_key__'] = primary_key attrs['__sql__'] = lambda self:_gen_sql(attrs['__table__'],mappings) #用于生成对应的表,传入参数包含表名字attrs['__table__'],和表中每一行包含的数据项目mappings for trigger in _triggers: if not trigger in attrs: attrs[trigger] = None return type.__new__(cls,name,bases,attrs)
def __getPicsExifInfo(self, files): ''' read out exif information in specific file :param files: filename list :return: dict of date information ''' picsDateInfo = {} for picture in files: # Read exif date information with open(picture, 'rb') as fd: pictureDate = "" pictureExifInfo = exifread.process_file(fd) try: if pictureExifInfo.__contains__('EXIF DateTimeOriginal'): tempStr = pictureExifInfo['EXIF DateTimeOriginal'] pictureDate = str(tempStr).replace(':', '-')[:10] elif pictureExifInfo.__contains__( 'EXIF DateTimeDigitized'): tempStr = pictureExifInfo['EXIF DateTimeDigitized'] pictureDate = str(tempStr).replace(':', '-')[:10] else: logging.info( 'No EXIF DateTimeOriginal: {}'.format(picture)) except: logging.warnning( "Can't do exif.process {}".format(picture)) # A picture hasn't date information, so according to file time # to set up a date to it if pictureDate == '': tc = time.localtime(os.path.getctime(picture)) pictureDate = time.strftime('%Y-%m-%d', tc) # set up dict { date : [filename] } if not picsDateInfo.__contains__(pictureDate): picsDateInfo[pictureDate] = [picture] else: picsDateInfo[pictureDate].append(picture) logging.info('classifying file: {}'.format(picture)) return picsDateInfo
def main(): fileList = os.listdir(appPath) moduleList = [x.replace('.py', '') for x in fileList] for m in moduleList: importCmd = 'from {0} import {1} as {0}'.format(m, 'main') exceptMsg = '{}不存在'.format(m) execCmd = '{}()'.format(m) errorLog = '{}数据获取失败'.format(m) infoLog = '{}数据获取成功'.format(m) try: exec(importCmd) except Exception as e: logging.warnning(exceptMsg, e) else: try: exec(execCmd) except Execption as e: logging.error(errorLog) else: logging.info(infoLog)
def add_cart(request): if request.method == "POST": user = request.user goodsid = request.POST.get("goodsid", "") amount = request.POST.get("amount", "") new_cart = Cart() try: goods = GoodsDetail.objects.get(id=goodsid) except DatabaseError as e: logging.warnning(e) oldcart = Cart.objects.filter(user_id=user.id, goods_id=goodsid) if oldcart: oldcart[0].amount = oldcart[0].amount + amount oldcart[0].save() else: new_cart.user = user new_cart.goods = goods new_cart.amount = int(amount) new_cart.save() return HttpResponse(json.dumps({'result':"添加成功"})) elif request.method == "GET": pass
def __new__(cls, name, bases, attrs): #skip base model class: if name=='Model': return type.__new__(cls, name, bases, attrs) #store all subclasses info: if not hasattr(cls, 'subclasses'): cls.subclasses = {} if not name in cls.subclasses: cls.subclasses[name] = name else: logging.warnning('Redefin class: %s' % name) logging.info('Scan ORMapping %s...' % name) mappings = dict() primary_key = None for k,v in attrs.iteriterms(): if isinstance(v,Field): if not v.name: v.name = k logging.info('Found mappings: %s => %s' % (k,v)) #check duplicate primary key: if v.primary_key: if primary_key: raise TypeError('Cannot define more than 1 primary key in class: %s' % name) if v.updatable: logging.warnning('Note: change primary key to non-updatable.') v.updatable = False; if v.nullable: logging.warnning('Note: change primary key to non-nullable.') v.nullable = False primary_key = v mappings[k] = v #check exist of primary key: if not primary_key: raise TypeError('Primary key not defined in class: %s' % name) for k in mappings.iterkeys(): attrs.pop(k) if not '__table__' in attrs: attrs['__table__'] = name.lower() attrs['__mapppings__'] = mappings attrs['__primary_key__'] = primary_key attrs['__sql__'] = lambda self:_gen_sql(attrs['__table__'],mappings) for trigger in _triggers: if not trigger in attrs: attrs[trigger] = None return type.__new__(cls, name, bases, attrs)
def log_warn(self,msg): logging.warnning(msg)
def __call__(self, request): kw = None # 首先从request获取所有能够获得的参数,然后再去决定如何传参。 if self._has_var_kw_arg or self._has_named_kw_args or self._required_kw_args: if request.method == "POST": if not request.content_type: logging.info("11111111111111111111111111111") return web.HTTPBadRequest('Missing Content-Type') ct = request.content_type.lower() if ct.startswith("application/json"): params = yield from request.json() logging.info(params) if not isinstance(params, dict): logging.info("22222222222222222222222222222") return web.HTTPBadRequest("JSON body must be object") # 刚才,搞忘了这一句出错了 kw = params elif ct.startswith("application/x-www-form-urlencoded" ) or ct.startswith("multipart/form-data"): params = yield from request.post() kw = dict(**params) else: logging.info("3333333333333333333333333333333333") return web.HTTPBadRequest("Unsupported Content-type: %s" % request.content_type) if request.method == "GET": # 查询字符串 qs = request.query_string if qs: kw = dict() for k, v in parse.parse_qs(qs, True).items(): kw[k] = v[0] # 未从request中获取到参数 if kw is None: # request.match_info是一个dict kw = dict(**request.match_info) else: # url处理函数没有VAR_KEYWORD 只有KEYWORD_ONLY # 从request_content中删除URL处理函数中所有不需要的参数 if not self._has_var_kw_arg and self._named_kw_args: copy = dict() for name in self._named_kw_args: if name in kw: copy[name] = kw[name] kw = copy for k, v in request.match_info.items(): if k in kw: logging.warnning( 'Duplicate arg name in named arg and kw args: %s' % k) kw[k] = v if self._has_request_arg: kw['request'] = request # 之前默认为空的关键字,必须传入参数。检查kw中是否已经获得这些参数 if self._required_kw_args: for name in self._required_kw_args: if name not in kw: logging.info("4444444444444444444444444444444444444") # return web.HTTPBadRequest() return web.HTTPBadRequest('Missing argument: %s' % name) logging.info("call with args: %s" % str(kw)) logging.info(str(self._func)) try: r = yield from self._func(**kw) return r # understand ?? how to use ? Inside the handler. except APIError as e: return dict(error=e.error, data=e.data, message=e.message)
def __new__(cls, name, bases, attrs): # __new__ 是在__init__之前被调用的特殊方法 # __new__是用来创建对象并返回之的方法 # 而__init__只是用来将传入的参数初始化给对象 # 你很少用到__new__,除非你希望能够控制对象的创建 # 这里,创建的对象是类,我们希望能够自定义它,所以我们这里改写__new__ # 如果你希望的话,你也可以在__init__中做些事情 # 还有一些高级的用法会涉及到改写__call__特殊方法,但是我们这里不用 # print '*' * 50 # print 'cls: %s' %cls # print 'name: %s' %name # print 'bases: %s' %bases # print 'attrs: %s' %attrs # print '*' * 50 if name == 'Model': return type.__new__(cls, name, bases, attrs) if not hasattr(cls, 'subclasses'): cls.subclasses = {} if not name in cls.subclasses: cls.subclasses[name] = name else: logging.warnning('Redefine class %s' % name) logging.info("Scan ORMmapping... %s " % name) mappings = dict() primary_key = None for k, v in attrs.iteritems(): if isinstance(v, Field): if not v.name: v.name = k logging.info('Found Map : %s => %s' %(k, v)) if v.primary_key: if primary_key: raise TypeError('Cannot define more than one primary_key...') if v.updatable: logging.warning('Note: change primary_key to non-updatable') v.updatable = False if v.nullable: logging.warning('Node: change primary_key to non-nullable') primary_key = v mappings[k] = v if not primary_key: raise TypeError('primary_key not defined in class: %s' % name) for k in mappings.iterkeys(): attrs.pop(k) if not '__table__' in attrs: attrs['__table__'] = name.lower() attrs['__mappings__'] = mappings attrs['__primary_key__'] = primary_key attrs['__sql__'] = lambda self : _gen_sql(attrs['__table__'], mappings) for trigger in _triggers: if not trigger in attrs: attrs[trigger] = None return type.__new__(cls, name, bases, attrs)
#!/usr/bin/env python3 # 简单日志输出: # 导入日志模块 import logging # 简单级别日志输出: logging.debug('[debug 日志]') logging.info(('[info 日志]') logging.warnning('[warnning 日志]') logging.error('[error 日志]') logging.critical('[critical 日志]')
async def remove(self): args = [self.getValue(self.__primary_key__)] rows = await execute(self.__delete__, args) if rows != 1: logging.warnning( 'failed to remove by primary key: affected rows: %s' % rows)
def __call__(self, request): kw = None # 首先从request获取所有能够获得的参数,然后再去决定如何传参。 if self._has_var_kw_arg or self._has_named_kw_args or self._required_kw_args: if request.method == "POST": if not request.content_type: logging.info("11111111111111111111111111111") return web.HTTPBadRequest('Missing Content-Type') ct = request.content_type.lower() if ct.startswith("application/json"): params = yield from request.json() logging.info(params) if not isinstance(params, dict): logging.info("22222222222222222222222222222") return web.HTTPBadRequest("JSON body must be object") # 刚才,搞忘了这一句出错了 kw = params elif ct.startswith("application/x-www-form-urlencoded") or ct.startswith("multipart/form-data"): params = yield from request.post() kw = dict(**params) else: logging.info("3333333333333333333333333333333333") return web.HTTPBadRequest("Unsupported Content-type: %s" % request.content_type) if request.method == "GET": # 查询字符串 qs = request.query_string if qs: kw = dict() for k, v in parse.parse_qs(qs, True).items(): kw[k] = v[0] # 未从request中获取到参数 if kw is None: # request.match_info是一个dict kw = dict(**request.match_info) else: # url处理函数没有VAR_KEYWORD 只有KEYWORD_ONLY # 从request_content中删除URL处理函数中所有不需要的参数 if not self._has_var_kw_arg and self._named_kw_args: copy = dict() for name in self._named_kw_args: if name in kw: copy[name] = kw[name] kw = copy for k, v in request.match_info.items(): if k in kw: logging.warnning('Duplicate arg name in named arg and kw args: %s' % k) kw[k] = v if self._has_request_arg: kw['request'] = request # 之前默认为空的关键字,必须传入参数。检查kw中是否已经获得这些参数 if self._required_kw_args: for name in self._required_kw_args: if name not in kw: logging.info("4444444444444444444444444444444444444") # return web.HTTPBadRequest() return web.HTTPBadRequest('Missing argument: %s' % name) logging.info("call with args: %s" % str(kw)) logging.info(str(self._func)) try: r = yield from self._func(**kw) return r # understand ?? how to use ? Inside the handler. except APIError as e: return dict(error=e.error, data=e.data, message=e.message)
def _profiling(start,sql =''): t = time.time() - start if t > 0.1: logging.warnning('[PROFILING][DB] %s : %s' %(t,sql)) else: logging.info('[PROFILING][DB] %s : %s' %(t,sql))