def __init__(self, ctxt): Component.__init__(self, ctxt) self.ctxt = ctxt log.debug("Reached the first check-point.") self.Monitoring = ctxt.resolve( "nox.netapps.monitoring.monitoring.Monitoring") log.debug("Reached the second check-point.")
def socks_method_CONNECT(self): # Check if we have ip address or domain name # log.debug("socks_method_CONNECT host = " + self.host) # The FaceTime SOCKS5 proxy treats IP addr the same way as hostname # if _ip_regex.match (self.host): # # we have dotted quad IP address # addressType = 1 # address = socket.inet_aton (self.host) # else: # # we have host name # address = self.host # addressType = 3 address = self.host addressType = 3 addressLen = len(address) # Protocol version=5, Command=1 (CONNECT), Reserved=0 # command = struct.pack ("!BBBB", 5, 1, 0, addressType) command = struct.pack("!BBBBB", 5, 1, 0, addressType, addressLen) portstr = struct.pack("!H", self.port) self.transport.write(command + address + portstr) self.state = "gotConnectReply"
def answer(self, transport, recipient, message): user = self.auth.authenticate(recipient) if user: session = USSDSession.objects.recent(user) if session: log.debug("User: %s USSD Session: %s" % (user, session)) msg = str(message) if msg == "$start": response = handle_start(session) elif msg == "$end": response = handle_end(session) elif msg == "$error": import pdb pdb.set_trace() else: if session.current_menu and not session.current_menu.is_finished(): response = handle_session(session, msg) else: response = "Use $start to create menu" if recipient and response: transport(recipient, response) else: log.error("Either recipient (%s) or response (%s) is not valid!" % (recipient, response)) return else: transport(recipient, "Error: No USSD Session!") else: transport(recipient, "Error: No User!")
def dispatch(self, msg): match = self.regex.search(msg) if not match: log.debug('Failed to match snort rule-sid in msg: {!r}'.format(msg)) return msg sid = match.group('sid') if self.gid_ignore: try: gid = match.group('gid') except IndexError: pass else: if gid in self.gid_ignore: return msg ts = time() if self.sid_db_ts < ts - self.conf.sid_db_mtime_check_interval: if not os.path.exists(self.conf.paths.sid_db)\ or max(0, *( os.stat(p).st_mtime for p in [self.conf.paths.sid_src, self.conf.paths.refs] if os.path.exists(p) )) > os.stat(self.conf.paths.sid_db).st_mtime: self.update_sid_db() self.sid_db = anydbm.open(self.conf.paths.sid_db) try: ref = force_unicode(self.sid_db[force_bytes(sid)]) except KeyError: log.info('Failed to find refs for sid: {!r} (msg: {!r})'.format(sid, msg)) else: msg += u'\n refs: {}'.format(ref) return msg
def dispatch(self, msg): # Get the artifact signature id match = self.regex.search(msg) if not match: log.debug('Failed to match snort rule-signature in msg: {!r}'.format(msg)) return msg sig = match.group('sig') # Check if traffic dump should be generated dump = False if self.conf.traffic_dump.match_exclude: for regex in self.conf.traffic_dump.match_exclude: if re.search(regex, msg): dump = None break if dump is not None: if sig in self.conf.traffic_dump.signatures: dump = True if not dump and self.conf.traffic_dump.match: for regex in self.conf.traffic_dump.match: if re.search(regex, msg): dump = True break if dump: try: dump = self.traffic_dump() except Exception as err: msg += '\n dump failed: {}'.format(err) else: msg += '\n dump: {}'.format(dump) return msg
def socks_method_CONNECT (self): # Check if we have ip address or domain name # log.debug("socks_method_CONNECT host = " + self.host) # The FaceTime SOCKS5 proxy treats IP addr the same way as hostname # if _ip_regex.match (self.host): # # we have dotted quad IP address # addressType = 1 # address = socket.inet_aton (self.host) # else: # # we have host name # address = self.host # addressType = 3 address = self.host addressType = 3 addressLen = len(address) #Protocol version=5, Command=1 (CONNECT), Reserved=0 #command = struct.pack ("!BBBB", 5, 1, 0, addressType) command = struct.pack ("!BBBBB", 5, 1, 0, addressType,addressLen) portstr = struct.pack ("!H", self.port) self.transport.write (command + address + portstr) self.state = "gotConnectReply"
def dispatch(self, msg): for pat, pat_re in self.patterns.viewitems(): if pat_re.search(msg): log.debug("Matched nflog-dump pattern: {}".format(pat)) break else: return ts = time() if self.conf.traffic_dump.min_interval and self.last_dump > ts - self.conf.traffic_dump.min_interval: log.debug( "Ignoring nflog-dump pattern match" " ({}) due to rate-limiting (elapsed: {:.1f}, min: {})".format( pat, ts - self.last_dump, self.conf.traffic_dump.min_interval ) ) return self.last_dump = ts msg = "Matched nflog-dump pattern: {}".format(pat) try: dump = self.traffic_dump(ts=ts) except Exception as err: msg += "\n dump failed: {}".format(err) else: msg += "\n dump: {}".format(dump) return msg
def queue(self, id, op): if not self.connected: raise LDAPServerConnectionLostException() msg = pureldap.LDAPMessage(op, id=id) if self.debug: log.debug('S->C %s' % repr(msg)) self.transport.write(str(msg))
def socks_gotHelloReply (self, data): """ Receive server greeting and send authentication or ask to execute requested method right now. """ if data == "\x05\xFF": # No acceptable methods. We MUST close # log.debug("No acceptable methods, closing connection") self.transport.loseConnection() return elif data == "\x05\x00": # Anonymous access allowed - let's issue connect # self.sendCurrentMethod() elif data == "\x05\x02": # Authentication required # self.sendAuth() else: self.transport.loseConnection() self.factory.clientConnectionFailed (self, failure.Failure ( UnhandledData ("Server returned unknown reply in gotHelloReply"))) # From now on SOCKS server considered alive - we've got reply # self.factory.status = "connected"
def succeed(*args, **kwargs): log.debug("ClientQueue: success, queue size %d, reqs out %d" % (len(self.queue), self.count)) self.count -= 1 try: success(*args, **kwargs) except Exception, e: log.err("Exception '%s' in ClientQueue callback; moving on" % str(e))
def run(self): log.debug('[Task] running') self._running = True self._aborted = False o = (self.fnc, self.args, self.kwargs, self.onComplete) fnc_queue.put(o)
def preApplication(self): """ We don't actually want to override this method since there is nothing interesting to do in here. """ log.debug("[D] %s %s " % (__file__, __name__), "Class GLBaseRunner", "preApplication") pass
def __reduce(self): """Pull stuff off the queue.""" #only need to reduce if there is more than one item in the queue if len(self.queue) == 1: #if we've received all the results from all the shards #and the queue only has 1 element in it, then we're done reducing if self.num_entries_remaining == 0 and self.reduces_out == 0: # if this was a count query, slice stuff off if self.count is not None: log.debug("count: %d, skip: %d, results: %d" % (self.count, self.skip, len(self.queue[0]['rows']))) self.queue[0]['rows'] = self.queue[0]['rows'][self.skip:self.skip+self.count] elif self.skip > 0: self.queue[0]['rows'] = self.queue[0]['rows'][self.skip:] body = cjson.encode(self.queue[0]) # filter headers that should not be reverse proxied strip_headers = ['content-length', 'etag'] headers = dict([(k,v) for k,v in self.headersrecvd.iteritems() if k.lower() not in strip_headers]) # calculate a deterministic etag nodes = self.etags.keys() nodes.sort() # sum in deterministic order md5etag = md5.md5() for node in nodes: md5etag.update(self.etags[node]) if len(nodes) > 0: headers['etag'] = ['"%s"' % md5etag.hexdigest()] log.debug("Reducer: response headers = %s" % str(headers)) self.reduce_deferred.callback((self.coderecvd, headers, body)) return a,b = self.queue[:2] self.queue = self.queue[2:] # hand the work off to _do_reduce, which we can override self._do_reduce(a,b)
def socks_gotHelloReply(self, data): """ Receive server greeting and send authentication or ask to execute requested method right now. """ if data == "\x05\xFF": # No acceptable methods. We MUST close # log.debug("No acceptable methods, closing connection") self.transport.loseConnection() return elif data == "\x05\x00": # Anonymous access allowed - let's issue connect # self.sendCurrentMethod() elif data == "\x05\x02": # Authentication required # self.sendAuth() else: self.transport.loseConnection() self.factory.clientConnectionFailed(self, failure.Failure( UnhandledData( "Server returned unknown reply in gotHelloReply"))) # From now on SOCKS server considered alive - we've got reply # self.factory.status = "connected"
def dataReceived(self, recd): self.recvd = self.recvd + recd while len(self.recvd) >= 10: # hack for DeLorme EarthMate if self.recvd[:8] == 'EARTHA\r\n': if self.allow_earthmate_hack: self.allow_earthmate_hack = 0 self.transport.write('EARTHA\r\n') self.recvd = self.recvd[8:] continue if self.recvd[0:2] != '\xFF\x81': if DEBUG: raise ZodiacParseError('Invalid Sync %r' % self.recvd) else: raise ZodiacParseError sync, msg_id, length, acknak, checksum = struct.unpack('<HHHHh', self.recvd[:10]) # verify checksum cksum = -(reduce(operator.add, (sync, msg_id, length, acknak)) & 0xFFFF) cksum, = struct.unpack('<h', struct.pack('<h', cksum)) if cksum != checksum: if DEBUG: raise ZodiacParseError('Invalid Header Checksum %r != %r %r' % (checksum, cksum, self.recvd[:8])) else: raise ZodiacParseError # length was in words, now it's bytes length = length * 2 # do we need more data ? neededBytes = 10 if length: neededBytes += length + 2 if len(self.recvd) < neededBytes: break if neededBytes > self.MAX_LENGTH: raise ZodiacParseError("Invalid Header??") # empty messages pass empty strings message = '' # does this message have data ? if length: message, checksum = self.recvd[10:10+length], struct.unpack('<h', self.recvd[10+length:neededBytes])[0] cksum = 0x10000 - (reduce(operator.add, struct.unpack('<%dH' % (length/2), message)) & 0xFFFF) cksum, = struct.unpack('<h', struct.pack('<h', cksum)) if cksum != checksum: if DEBUG: log.debug('msg_id = %r length = %r' % (msg_id, length)) raise ZodiacParseError('Invalid Data Checksum %r != %r %r' % (checksum, cksum, message)) else: raise ZodiacParseError # discard used buffer, dispatch message self.recvd = self.recvd[neededBytes:] self.receivedMessage(msg_id, message, acknak)
def dataReceived(self, data): recs = data.strip().split('\n') for rec in recs: self.model.feedAccumulator(rec) if self.model.hasEnoughData(): log.debug("Model has enough data to execute the loop...") self.model.run()
def send_flow_stats_request_timer(self, dpid): log.debug("I am able to enter the flow_stats_request_timer method.") global xid flows = of.ofp_match() flows.wildcards = of.OFPFW_ALL #wildcarded all match fields, which means that all the flows will be retrieved. self.Monitoring.send_flow_stats_request(dpid, flows, 0xff, xid) xid += 1 self.post_callback(FLOW_MONITOR_INTERVAL, lambda : self.send_flow_stats_request_timer(dpid))
def inform(): if len(obs.orderbook.bids) > 0: try: print("Highest bid {:.2f}, lowest ask {:.2f}; lowest bid {:.2f} and highest ask {:.2f}.".format( obs.highestbid, obs.lowestask, obs.orderbook.bids[-1].price, obs.orderbook.asks[-1].price)) pass except TypeError as e: log.debug("Error: {0}".format(e.message))
def _send(self, op): if not self.connected: raise LDAPClientConnectionLostException() msg = pureldap.LDAPMessage(op) if self.debug: log.debug('C->S %s' % repr(msg)) assert not self.onwire.has_key(msg.id) return msg
def twisted_log(eventDict): log = logging.getLogger('twisted') if 'failure' in eventDict: log.error(eventDict.get('why') or 'Unhandled exception' + '\n' + str(eventDict['failure'].getTraceback())) elif 'warning' in eventDict: log.warning(eventDict['warning']) else: log.debug(' '.join([str(m) for m in eventDict['message']]))
def _send(self, op): if not self.connected: raise LDAPClientConnectionLostException() msg=pureldap.LDAPMessage(op) if self.debug: log.debug('C->S %s' % repr(msg)) assert not self.onwire.has_key(msg.id) return msg
def _sendResponse(self, data, request, requestID, error=''): response = json.dumps( {'request': request, 'requestID': requestID, 'data': data, 'error': error} ) log.debug('Sending response: %s' % response) self.sendString(response)
def log_error(err, n): if err.check(protocol.TimeoutError): log.debug("Timeout while storing blob_hash %s at %s", binascii.hexlify(blob_hash), n) else: log.error( "Unexpected error while storing blob_hash %s at %s: %s", binascii.hexlify(blob_hash), n, err.getErrorMessage())
def childDataReceived(self, childFD, response): log.debug("Received data from reducer %s" % response) if childFD == 1: self.response += response # should get one line back for each line we sent (plus one for trailing newline) response_lines = len(self.response.split("\n")) if response_lines>len(self.lines): self._deferred.callback( (self.keys, self.response) )
def chat(self, to, body): message = domish.Element((None, 'message')) message['to'] = to message['from'] = self.parent.jid.full() message['type'] = 'chat' message.addElement('body', content=body) self.xmlstream.send(message) log.debug(u"Sent %s message (len=%d) to %s: %s" % (message['type'], len(str(message.body)), message['to'], message.body))
def fail(*args, **kwargs): log.debug("ClientQueue: failure, queue size %d, reqs out %d" % (len(self.queue), self.count)) self.count -= 1 try: err(*args, **kwargs) except: log.err("Exception in ClientQueue errback; moving on") self.next()
def runApp(res): """ Start the actual service Application. """ log.debug("[D] %s %s " % (__file__, __name__), "Class GLBaseRunner", "preApplication", "runApp") service.IService(self.application).privilegedStartService() app.startApplication(self.application, not self.config['no_save']) app.startApplication(internet.TimerService(0.1, lambda:None), 0) startAsynchronous()
def send_flow_stats_request_timer(self, dpid): log.debug("I am able to enter the flow_stats_request_timer method.") global xid flows = of.ofp_match() flows.wildcards = of.OFPFW_ALL #wildcarded all match fields, which means that all the flows will be retrieved. self.Monitoring.send_flow_stats_request(dpid, flows, 0xff, xid) xid += 1 self.post_callback(FLOW_MONITOR_INTERVAL, lambda: self.send_flow_stats_request_timer(dpid))
def packet_in_callback(self, dpid, inport, reason, len, bufid, packet): """Packet-in handler""" if not packet.parsed: log.debug('Ignoring incomplete packet') else: self.learn_and_forward(dpid, inport, packet, packet.arr, bufid) return CONTINUE
def lineReceived(self, line): log.debug("{line!r}", line=line) try: data = self.serializer.loads(line.rstrip()) self.process_line_data(data, line) except Exception, e: log.failure("{message!r}", message=e.message) log.error("{line!r}", line=line)
def postApplication(self): """ We must place all the operations to be done before the starting of the application. Here we will take care of the launching of the reactor and the operations to be done after it's shutdown. """ log.debug("[D] %s %s " % (__file__, __name__), "Class GLBaseRunner", "postApplication") pass
def __init__(self, callback, fnc, *args, **kwargs): log.debug('[Task] initializing') Task.instance = self self.callback = callback self.fnc = fnc self.args = args self.kwargs = kwargs self._running = False self._aborted = False
def log_error(err, n): if err.check(protocol.TimeoutError): log.debug( "Timeout while storing blob_hash %s at %s", binascii.hexlify(blob_hash), n) else: log.error( "Unexpected error while storing blob_hash %s at %s: %s", binascii.hexlify(blob_hash), n, err.getErrorMessage())
def runApp(res): """ Start the actual service Application. """ log.debug("[D] %s %s " % (__file__, __name__), "Class GLBaseRunnerUnix", "postApplication", "runApp") print "Running start." self.startApplication(self.application) startAsynchronous() print "GLBackend is now running" print "Visit http://127.0.0.1:8082/index.html to interact with me"
def twisted_log(eventDict): log = logging.getLogger('twisted') if 'failure' in eventDict: log.error( eventDict.get('why') or 'Unhandled exception' + '\n' + str(eventDict['failure'].getTraceback())) elif 'warning' in eventDict: log.warning(eventDict['warning']) else: log.debug(' '.join([str(m) for m in eventDict['message']]))
def proto_on(self, irc): self.proto = irc for alias, channel in self.channels.viewitems(): channel = channel.get('name') or alias if channel[0] not in self.chan_prefix: log.debug( 'Not joining channel' ' w/o channel-specific prefiix: {}'.format(channel) ) continue log.debug('Joining channel: {}'.format(channel)) self.proto.join(channel)
def __init__( self, paths_watch, callback, errback, mask=inotify.IN_CREATE | inotify.IN_MODIFY ): inotify.INotify.__init__(self) # Might as well start it here self.startReading() self.errback = errback for path in paths_watch: log.debug('Adding watcher for path: {}'.format(path)) self.watch(path, mask=mask, callbacks=[callback])
def lineReceived(self, line): log.debug("--> %r" % line) unpack = line.split(None, 1) command, args = unpack[0], unpack[1:] try: handler = getattr(self, "ftp_%s" % command.upper()) except AttributeError: self.sendLine("502 Command not implemented") return d = defer.maybeDeferred(handler, *args) d.addErrback(self._error)
def convert(result): if hasattr(result, 'jsonState'): ret = result.jsonState() else: ret = result log.debug("result %s", str(ret)[:1000]) try: return json.serialize(ret) except TypeError, e: # out of sync with mpd? let supervisor restart us raise SystemExit("result %r, error %r" % (result, e))
def create_db(): ret = False if not os.path.isfile(unique_id_db): log.debug("create unique_id_db database") conn = sqlite3.connect(unique_id_db) conn.isolation_level = None c = conn.cursor() c.execute("""create table rtid (data text)""") conn.commit() c.close() conn.close()
def startWorkerThread(): log.debug("[Task] starting workerThread") global m_pump_conn if m_pump_conn is not None: del m_pump_conn global m_pump if m_pump is None: m_pump = ePythonMessagePump() m_pump_conn = eConnectCallback(m_pump.recv_msg, run_in_main_thread) Task.worker_thread = WorkerThread() Task.worker_thread.start()
def registerNodeInactivity(self, nodeId): """updates last_sleep_time attribute""" cursor = self._cnx.cursor() nodes = Node.selectWhere(cursor, node_id=nodeId) if nodes: node = nodes[0] node.last_sleep_time = int(time.time()) node.commit(cursor, update=True) else: log.debug('No matching node found for id {%s}' % nodeId, category='[warning]') cursor.close()
def connectionMade(self): # prepare connection string with available authentication methods # log.debug ("SOCKS5.connectionMade") methods = "\x00" if not self.login is None: methods += "\x02" connstring = struct.pack ("!BB", 5, len (methods)) self.transport.write (connstring + methods) self.state = "gotHelloReply"
def wrapped(*args, **kwargs): def _callFromThread(): result = defer.maybeDeferred(func, *args, **kwargs) result.addBoth(fnc_in_queue.put) fnc_out_queue.put(_callFromThread) m_pump.send(0) result = fnc_in_queue.get() log.debug("result is %s" % str(result)) if isinstance(result, failure.Failure): result.raiseException() return result
def db_list_rtid(): conn = sqlite3.connect(unique_id_db) conn.isolation_level = None c = conn.cursor() c.execute("""select data from rtid""") log.debug("fetch content from unique_id_db DB") ret = [] for r in c: if r not in ret: ret.append(r[0]) c.close() conn.close() return ret
def save_bans(self): ban_file = os.path.join(config.config_dir, 'bans.txt') ensure_dir_exists(ban_file) start_time = reactor.seconds() with open(ban_file, 'w') as f: json.dump(self.bans.make_list(), f, indent=2) log.debug("saving {count} bans took {time} seconds", count=len(self.bans), time=reactor.seconds() - start_time) if self.ban_publish is not None: self.ban_publish.update()
def stopWorkerThread(): log.debug("[Task] stopping workerThread") Task.worker_thread.stop() Task.worker_thread.join() Task.worker_thread = None global m_pump_conn if m_pump_conn is not None: del m_pump_conn m_pump_conn = None global m_pump if m_pump is not None: m_pump.stop() m_pump = None
def locateChild(self, ctx, segments): methodName = segments[0] if methodName == 'lsinfoTree': return self.child_lsinfoTree(ctx), [] local = getattr(self, 'child_' + methodName, None) if local is not None: return local(ctx), [] if methodName.startswith('_'): raise ValueError("command: %s" % methodName) mpdMethod = getattr(self.mpd, methodName) callArgs = argsFromPostOrGet(mpdMethod, postDataFromCtx(ctx), ctx) log.debug("Command: %s(%r)", mpdMethod.__name__, callArgs) return JsonResult(mpdMethod(**callArgs)), []
def process_ack(self, uid_conversation, ack=1): if uid_conversation in self.factory.waiting_acks: log.debug('Processing ack for conversation %s' % (uid_conversation, )) data = {'ack': ack, 'uid_conversation': uid_conversation} channel = self.factory.waiting_acks[uid_conversation]["channel"] channel.sendLine(self.serializer.dumps(data)) del self.factory.waiting_acks[uid_conversation] if uid_conversation in self.factory.conversation_callbacks: self.factory.conversation_callbacks[uid_conversation].cancel() del self.factory.conversation_callbacks[uid_conversation] else: log.warn('Tried to process an ack that is not present %s' % (uid_conversation, ))
def syscall(bin, parameters): # system call, wait for process to finish and capture the stdout/stderr output syscmd = ' '.join([bin] + parameters) log.debug("execute command: %s" % syscmd) p = subprocess.Popen(syscmd, bufsize=65536, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = 0 if 'Windows' != platform.system(): retcode = p.wait() (child_stdout, child_stderr) = (p.stdout, p.stderr) return retcode, (child_stdout.read(), child_stderr.read())
def registerNodeActivity(self, nodeId): """updates last_seen_time attribute""" cursor = self._cnx.cursor() nodes = Node.selectWhere(cursor, node_id=nodeId) if nodes: node = nodes[0] print " ... registerNodeActivity %s:%s (%s)" % (node.ip, node.port, nodeId) node.last_seen_time = int(time.time()) node.commit(cursor, update=True) else: #FIXME: that's not a warning but a BUG log.debug('No matching node found for id {%s}' % nodeId, category='[warning]') cursor.close()
def handle(self, msg): assert isinstance(msg.value, pureldap.LDAPProtocolRequest) if self.debug: log.debug('S<-C %s' % repr(msg)) if msg.id == 0: self.unsolicitedNotification(msg.value) else: name = msg.value.__class__.__name__ handler = getattr(self, 'handle_' + name, self.handleUnknown) d = defer.maybeDeferred( handler, msg.value, msg.controls, lambda response: self._cbHandle(response, msg.id)) d.addErrback(self._cbLDAPError, name) d.addErrback(defer.logError) d.addErrback(self._cbOtherError, name) d.addCallback(self._cbHandle, msg.id)
def handle_barrier_reply(self, dpid, xid): # find the pending route this xid belongs to intxid = c_ntohl(xid) for pending_route in self.pending_routes[:]: if intxid in pending_route: pending_route.remove(intxid) # If this was the last pending barrier_reply_xid in this route if len(pending_route) == 1: log.debug("All Barriers back, sending packetout") indatapath, inport, event = pending_route[0] self.routing.send_packet(indatapath, inport, \ openflow.OFPP_TABLE,event.buffer_id,event.buf,"", \ False, event.flow) self.pending_routes.remove(pending_route) return STOP
def onComplete(self, success, result): def wrapped_finish(): Task.instance = None self.callback(success, result) if success: log.debug('[Task] completed with success') else: log.debug('[Task] completed with failure') # To make sure that, when we abort processing of task, # that its always the same type of failure if self._aborted: success = False result = failure.Failure(AddonThreadException()) fnc_out_queue.put(wrapped_finish) m_pump.send(0)
def remove_p_id(self, p_id): db = self.presentation_root_folder.db try: del db.presentation_atime_dict[p_id] except KeyError: pass try: p_state = db.presentation_states_dict[p_id] except KeyError: pass else: acl_token = p_state['acl_token'] for token in acl_token.values(): #if (token is None) or (token == ''): continue if not token: continue log.debug('removing token %s' % token) try: # 此數值 db.token_presentation_dict[token] 應該是p_id # 此處暫時不做一致性檢查 del db.token_presentation_dict[token] except KeyError: # 應該存在才合理 log.warn('token_presentation_dict db inconsistent type #1') try: db.delegate_host_dict[token] except KeyError: pass username = p_state['owner'] try: p_ids = db.user_presentation_dict[username] except KeyError: pass else: if p_id in p_ids: p_ids.remove(p_id) # 雖然 p_ids 可能是空的,但還是留著此紀錄,以保留 username之間的binding關係 db.user_presentation_dict[username] = p_ids else: log.warn('user_presentation_dict db inconsistent type #2') del db.presentation_states_dict[p_id]