desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname` to the ID if it\'s not the default, or to `False` if there isn\'t one. >>> db = DB(None, {}) >>> q = db.insert(\'foo\', name=\'bob\', age=2, created=SQLLiteral(\'NOW()\'), _test=True) >>> q <sql: "INSERT INTO foo (age, name, created) VALUES (2, \'bob\', NOW())"> >>> q.query() \'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())\' >>> q.values() [2, \'bob\']'
def insert(self, tablename, seqname=None, _test=False, **values):
def q(x): return (('(' + x) + ')') if values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query = (((('INSERT INTO %s ' % tablename) + q(_keys)) + ' VALUES ') + q(_values)) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query
'Inserts multiple rows into `tablename`. The `values` must be a list of dictioanries, one for each row to be inserted, each with the same set of keys. Returns the list of ids of the inserted rows. Set `seqname` to the ID if it\'s not the default, or to `False` if there isn\'t one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{"name": "foo", "email": "[email protected]"}, {"name": "bar", "email": "[email protected]"}] >>> db.multiple_insert(\'person\', values=values, _test=True) <sql: "INSERT INTO person (name, email) VALUES (\'foo\', \'[email protected]\'), (\'bar\', \'[email protected]\')">'
def multiple_insert(self, tablename, values, seqname=None, _test=False):
if (not values): return [] if (not self.supports_multiple_insert): out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if (seqname is False): return None else: return out keys = values[0].keys() for v in values: if (v.keys() != keys): raise ValueError, 'Bad data' sql_query = SQLQuery(('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys)))) for (i, row) in enumerate(values): if (i != 0): sql_query.append(', ') SQLQuery.join([SQLParam(row[k]) for k in keys], sep=', ', target=sql_query, prefix='(', suffix=')') if _test: return sql_query db_cursor = self._db_cursor() if (seqname is not False): sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): (q1, q2) = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(((out - len(values)) + 1), (out + 1)) except Exception: out = None if (not self.ctx.transactions): self.ctx.commit() return out
'Update `tables` with clause `where` (interpolated using `vars`) and setting `values`. >>> db = DB(None, {}) >>> name = \'Joseph\' >>> q = db.update(\'foo\', where=\'name = $name\', name=\'bob\', age=2, ... created=SQLLiteral(\'NOW()\'), vars=locals(), _test=True) >>> q <sql: "UPDATE foo SET age = 2, name = \'bob\', created = NOW() WHERE name = \'Joseph\'"> >>> q.query() \'UPDATE foo SET age = %s, name = %s, created = NOW() WHERE name = %s\' >>> q.values() [2, \'bob\', \'Joseph\']'
def update(self, tables, where, svars=None, _test=False, **values):
if (svars is None): svars = {} where = self._where(where, svars) query = ((((('UPDATE ' + sqllist(tables)) + ' SET ') + sqlwhere(values, ', ')) + ' WHERE ') + where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if (not self.ctx.transactions): self.ctx.commit() return db_cursor.rowcount
'Deletes from `table` with clauses `where` and `using`. >>> db = DB(None, {}) >>> name = \'Joe\' >>> db.delete(\'foo\', where=\'name = $name\', vars=locals(), _test=True) <sql: "DELETE FROM foo WHERE name = \'Joe\'">'
def delete(self, table, where, using=None, svars=None, _test=False):
if (svars is None): svars = {} where = self._where(where, svars) q = ('DELETE FROM ' + table) if using: q += (' USING ' + sqllist(using)) if where: q += (' WHERE ' + where) return q
'>>> aa = {\'host\':"localhost",\'user\':\'root\',\'passwd\':\'111\',\'db\':\'test\',\'port\':3306,\'charset\':\'utf8\'} >>> dbpool.initPool(**aa)'
def initPool(self, **kw):
self.config = kw creator = DBCS.get(kw.get('engine', 'mysql'), MySQLdb) self.pool = PooledDB(creator, 5, **kw)
''
def __init__(self, timeout=0):
self._hostname = '' self._urls = [] self.connection = None
'memcached 建立连接配眮连接信息 >>> mclient.connect([\'127.0.0.1:11211\'], "test")'
def connect(self, urls, hostname):
self._hostname = hostname self._urls = urls self.connection = memcache.Client(self._urls, debug=0) if (not self.connection.set('__testkey__', 1)): raise MemConnError()
'重新生成新的key规则是 _hostname:key >>> mclient.produceKey(\'name\') test:name'
def produceKey(self, keyname):
if isinstance(keyname, basestring): return str(''.join([self._hostname, ':', keyname])) else: raise 'type error'
''
def get(self, key):
key = self.produceKey(key) return self.connection.get(key)
''
def get_multi(self, keys):
keynamelist = [self.produceKey(keyname) for keyname in keys] olddict = self.connection.get_multi(keynamelist) newdict = dict(zip([keyname.split(':')[(-1)] for keyname in olddict.keys()], olddict.values())) return newdict
''
def set(self, keyname, value):
key = self.produceKey(keyname) result = self.connection.set(key, value) if (not result): self.connect(self._urls, self._hostname) return self.connection.set(key, value) return result
''
def set_multi(self, mapping):
newmapping = dict(zip([self.produceKey(keyname) for keyname in mapping.keys()], mapping.values())) result = self.connection.set_multi(newmapping) if result: self.connect(self._urls, self._hostname) return self.connection.set_multi(newmapping) return result
''
def incr(self, key, delta):
key = self.produceKey(key) return self.connection.incr(key, delta)
''
def delete(self, key):
key = self.produceKey(key) return self.connection.delete(key)
''
def delete_multi(self, keys):
keys = [self.produceKey(key) for key in keys] return self.connection.delete_multi(keys)
''
def flush_all(self):
self.connection.flush_all()
'@param name: str 对象的名称 @param _lock: int 对象锁 䞺1时衚瀺对象被锁定无法进行修改'
def __init__(self, name, mc):
self._client = mc self._name = name self._lock = 0
'重新生成key'
def produceKey(self, keyname):
if isinstance(keyname, basestring): return ''.join([self._name, ':', keyname]) else: raise 'type error'
''
def locked(self):
key = self.produceKey('_lock') return self._client.get(key)
''
def lock(self):
key = self.produceKey('_lock') self._client.set(key, 1)
''
def release(self):
key = self.produceKey('_lock') self._client.set(key, 0)
''
def get(self, key):
key = self.produceKey(key) return self._client.get(key)
'䞀次获取倚䞪key的倌 @param keys: list(str) key的列衚'
def get_multi(self, keys):
keynamelist = [self.produceKey(keyname) for keyname in keys] olddict = self._client.get_multi(keynamelist) newdict = dict(zip([keyname.split(':')[(-1)] for keyname in olddict.keys()], olddict.values())) return newdict
''
def update(self, key, values):
if self.locked(): return False key = self.produceKey(key) return self._client.set(key, values)
'同时修改倚䞪key倌'
def update_multi(self, mapping):
if self.locked(): return False newmapping = dict(zip([self.produceKey(keyname) for keyname in mapping.keys()], mapping.values())) return self._client.set_multi(newmapping)
'删陀memcache䞭的数据'
def mdelete(self):
nowdict = dict(self.__dict__) del nowdict['_client'] keys = nowdict.keys() keys = [self.produceKey(key) for key in keys] self._client.delete_multi(keys)
''
def incr(self, key, delta):
key = self.produceKey(key) return self._client.incr(key, delta)
''
def insert(self):
nowdict = dict(self.__dict__) del nowdict['_client'] newmapping = dict(zip([self.produceKey(keyname) for keyname in nowdict.keys()], nowdict.values())) self._client.set_multi(newmapping)
'@param HEAD_0: int 协议倎0 @param HEAD_1: int 协议倎1 @param HEAD_2: int 协议倎2 @param HEAD_3: int 协议倎3 @param protoVersion: int 协议倎版本号 @param serverVersion: int 服务版本号'
def __init__(self, HEAD_0=0, HEAD_1=0, HEAD_2=0, HEAD_3=0, protoVersion=0, serverVersion=0):
self.HEAD_0 = HEAD_0 self.HEAD_1 = HEAD_1 self.HEAD_2 = HEAD_2 self.HEAD_3 = HEAD_3 self.protoVersion = protoVersion self.serverVersion = serverVersion
''
def getHeadlength(self):
return 17
''
def unpack(self, dpack):
try: ud = struct.unpack('!sssss3I', dpack) except struct.error as de: log.err(de) return {'result': False, 'command': 0, 'length': 0} HEAD_0 = ord(ud[0]) HEAD_1 = ord(ud[1]) HEAD_2 = ord(ud[2]) HEAD_3 = ord(ud[3]) protoVersion = ord(ud[4]) serverVersion = ud[5] length = (ud[6] - 4) command = ud[7] if ((HEAD_0 != self.HEAD_0) or (HEAD_1 != self.HEAD_1) or (HEAD_2 != self.HEAD_2) or (HEAD_3 != self.HEAD_3) or (protoVersion != self.protoVersion) or (serverVersion != self.serverVersion)): return {'result': False, 'command': 0, 'length': 0} return {'result': True, 'command': command, 'length': length}
''
def pack(self, response, command):
HEAD_0 = chr(self.HEAD_0) HEAD_1 = chr(self.HEAD_1) HEAD_2 = chr(self.HEAD_2) HEAD_3 = chr(self.HEAD_3) protoVersion = chr(self.protoVersion) serverVersion = self.serverVersion length = (response.__len__() + 4) commandID = command data = struct.pack('!sssss3I', HEAD_0, HEAD_1, HEAD_2, HEAD_3, protoVersion, serverVersion, length, commandID) data = (data + response) return data
'@param _connections: dict {connID:conn Object}'
def __init__(self):
self._connections = {}
''
def getNowConnCnt(self):
return len(self._connections.items())
'@param _conn: Conn object'
def addConnection(self, conn):
_conn = Connection(conn) if self._connections.has_key(_conn.id): raise Exception('\xe7\xb3\xbb\xe7\xbb\x9f\xe8\xae\xb0\xe5\xbd\x95\xe5\x86\xb2\xe7\xaa\x81') self._connections[_conn.id] = _conn
'曎加连接的id删陀连接实䟋 @param connID: int 连接的id'
def dropConnectionByID(self, connID):
try: del self._connections[connID] except Exception as e: log.msg(str(e))
'根据ID获取䞀条连接 @param connID: int 连接的id'
def getConnectionByID(self, connID):
return self._connections.get(connID, None)
'根据连接ID䞻劚端口䞎客户端的连接'
def loseConnection(self, connID):
conn = self.getConnectionByID(connID) if conn: conn.loseConnection()
''
def pushObject(self, topicID, msg, sendList):
for target in sendList: try: conn = self.getConnectionByID(target) if conn: conn.safeToWriteData(topicID, msg) except Exception as e: log.err(str(e))
'id 连接的ID transport 连接的通道'
def __init__(self, _conn):
self.id = _conn.transport.sessionno self.instance = _conn
''
def loseConnection(self):
self.instance.transport.close()
''
def safeToWriteData(self, topicID, msg):
self.instance.safeToWriteData(msg, topicID)
''
def connectionMade(self):
address = self.transport.getAddress() log.msg(('Client %d login in.[%s,%d]' % (self.transport.sessionno, address[0], address[1]))) self.factory.connmanager.addConnection(self) self.factory.doConnectionMade(self)
''
def connectionLost(self, reason):
log.msg(('Client %d login out.' % self.transport.sessionno)) self.factory.doConnectionLost(self) self.factory.connmanager.dropConnectionByID(self.transport.sessionno)
'@param data: str 芁向客户端写的数据'
def safeToWriteData(self, data, command):
if (data is None): return senddata = self.factory.produceResult(data, command) self.transport.sendall(senddata)
'@param data: str 客户端䌠送过来的数据'
def dataReceived(self, data):
length = self.factory.dataprotocl.getHeadlength() self.buff += data while (self.buff.__len__() >= length): unpackdata = self.factory.dataprotocl.unpack(self.buff[:length]) if (not unpackdata.get('result')): log.msg('illegal data package --') self.factory.connmanager.loseConnection(self.transport.sessionno) break command = unpackdata.get('command') rlength = unpackdata.get('length') request = self.buff[length:(length + rlength)] if (request.__len__() < rlength): log.msg('some data lose') break self.buff = self.buff[(length + rlength):] response = self.factory.doDataReceived(self, command, request) if (not response): continue self.safeToWriteData(response, command)
''
def __init__(self, dataprotocl=DataPackProtoc()):
protocols.ServerFactory.__init__(self) self.service = None self.connmanager = ConnectionManager() self.dataprotocl = dataprotocl
''
def setDataProtocl(self, dataprotocl):
self.dataprotocl = dataprotocl
''
def doConnectionMade(self, conn):
pass
''
def doConnectionLost(self, conn):
pass
''
def addServiceChannel(self, service):
self.service = service
''
def doDataReceived(self, conn, commandID, data):
response = self.service.callTarget(commandID, conn, data) return response
'@param response: str 分垃匏客户端获取的结果'
def produceResult(self, command, response):
return self.dataprotocl.pack(command, response)
''
def loseConnection(self, connID):
self.connmanager.loseConnection(connID)
'@param topicID: int 消息的䞻题id号 @param msg: 消息的类容protobuf结构类型 @param sendList: 掚向的目标列衚(客户端id 列衚)'
def pushObject(self, topicID, msg, sendList):
self.connmanager.pushObject(topicID, msg, sendList)
''
def __init__(self):
self.configpath = None self.mainpath = None self.root = None self.webroot = None
''
def config(self, configpath, mainpath):
self.configpath = configpath self.mainpath = mainpath
''
def masterapp(self):
config = json.load(open(self.configpath, 'r')) GlobalObject().json_config = config mastercnf = config.get('master') rootport = mastercnf.get('rootport') webport = mastercnf.get('webport') masterlog = mastercnf.get('log') self.root = PBRoot() rootservice = services.Service('rootservice') self.root.addServiceChannel(rootservice) self.webroot = Flask('master') GlobalObject().root = self.root GlobalObject().webroot = self.webroot if masterlog: log.addObserver(loogoo(masterlog)) log.startLogging(sys.stdout) import webapp import rootapp reactor.listenWSGI(webport, self.webroot) reactor.listenTCP(rootport, BilateralFactory(self.root))
''
def start(self):
sys_args = sys.argv if ((len(sys_args) > 2) and (sys_args[1] == 'single')): server_name = sys_args[2] if (server_name == 'master'): mode = MASTER_SERVER_MODE else: mode = SINGLE_SERVER_MODE else: mode = MULTI_SERVER_MODE server_name = '' if (mode == MULTI_SERVER_MODE): self.masterapp() config = json.load(open(self.configpath, 'r')) sersconf = config.get('servers') for sername in sersconf.keys(): cmds = ('python %s %s %s' % (self.mainpath, sername, self.configpath)) subprocess.Popen(cmds, shell=True) reactor.run() elif (mode == SINGLE_SERVER_MODE): config = json.load(open(self.configpath, 'r')) sername = server_name cmds = ('python %s %s %s' % (self.mainpath, sername, self.configpath)) subprocess.Popen(cmds, shell=True) else: self.masterapp() reactor.run()
''
def setProxyReference(self, pr):
self.reference = pr
''
def getRemoteMethod(self, _name):
method = getattr(self.reference, ('remote_%s' % _name)) return method
'node节点端匀后的倄理'
def doconnectionLost(self):
if self.ro: self.ro.reconnect()
'@param port: int 远皋分垃服的端口号 @param rootaddr: 根节点服务噚地址'
def __init__(self, name, timeout=600):
self._name = name self._factory = BilateralClientFactory(self) self._reference = ProxyReference() self._addr = None self._timeout = timeout
''
def setName(self, name):
self._name = name
''
def getName(self):
return self._name
''
def connect(self, addr):
self._addr = addr reactor.connectTCP(addr[0], addr[1], self._factory) self.takeProxy()
''
def reconnect(self, addr=()):
if addr: self.connect(addr) else: self.connect(self._addr)
''
def addServiceChannel(self, service):
self._reference.addService(service)
''
def takeProxy(self):
self._factory._protocol.setProxyReference(self._reference) deferedRemote = self._factory.getRootObject(timeout=self._timeout) deferedRemote.callRemoteNotForResult('takeProxy', self._name)
''
def callRemote(self, commandId, *args, **kw):
deferedRemote = self._factory.getRootObject(timeout=self._timeout) return deferedRemote.callRemoteForResult('callTarget', commandId, *args, **kw)
''
def callRemoteForResult(self, commandId, *args, **kw):
deferedRemote = self._factory.getRootObject(timeout=self._timeout) return deferedRemote.callRemoteForResult('callTarget', commandId, *args, **kw)
''
def callRemoteNotForResult(self, commandId, *args, **kw):
deferedRemote = self._factory.getRootObject(timeout=self._timeout) return deferedRemote.callRemoteNotForResult('callTarget', commandId, *args, **kw)
''
def __init__(self):
self._childs = {}
''
def getChild(self, childname):
for (key, child) in self._childs.items(): if (child.getName() == childname): return self._childs[key] return None
'添加䞀䞪child节点 @param child: Child object'
def addChild(self, child):
key = child.getName() if self._childs.has_key(key): raise ('child node %s exists' % key) self._childs[key] = child
'删陀䞀䞪child 节点 @param child: Child Object'
def dropChild(self, child):
key = child.getName() try: del self._childs[key] except Exception as e: log.msg(str(e))
'删陀䞀䞪child 节点 @param childId: Child ID'
def dropChildByID(self, childId):
try: del self._childs[childId] except Exception as e: log.msg(str(e))
'@param childname: str 子节点的名称'
def callChild(self, childname, *args, **kw):
child = self.getChild(childname) if (not child): log.err(("child %s doesn't exists" % childname)) return return child.callbackChild(*args, **kw)
'@param childname: str 子节点的名称'
def callChildNotForResult(self, childname, *args, **kw):
child = self._childs.get(childname, None) if (not child): log.err(("child %s doesn't exists" % childname)) return child.callbackChildNotForResult(*args, **kw)
'根据sessionID获取child节点信息'
def getChildBYSessionId(self, session_id):
for child in self._childs.values(): if (child._transport.transport.sessionno == session_id): return child return None
''
def __init__(self, name):
self._name = name self._transport = None
''
def getName(self):
return self._name
''
def setTransport(self, transport):
self._transport = transport
'return a Defered Object (recvdata)'
def callbackChild(self, *args, **kw):
return self.callbackChildForResult(*args, **kw)
'return a Defered Object (recvdata)'
def callbackChildNotForResult(self, *args, **kw):
remote = self._transport.getRootObject() remote.callRemoteNotForResult('callChild', *args, **kw)
'return a Defered Object (recvdata)'
def callbackChildForResult(self, *args, **kw):
remote = self._transport.getRootObject() recvdata = remote.callRemoteForResult('callChild', *args, **kw) return recvdata
''
def __init__(self):
self._service = Service('proxy')
''
def addService(self, service):
self._service = service
''
def remote_callChild(self, command, *arg, **kw):
return self._service.callTarget(command, *arg, **kw)
'@param name: 根节点的名称'
def remote_takeProxy(self, name):
self.factory.root.remote_takeProxy(name, self)
'@param commandId: int 指什号 @param data: str 调甚参数'
def remote_callTarget(self, command, *args, **kw):
data = self.factory.root.remote_callTarget(command, *args, **kw) return data
''
def __init__(self, dnsmanager=ChildsManager()):
self.service = None self.childsmanager = dnsmanager
'@param service: Service Object(In bilateral.services)'
def addServiceChannel(self, service):
self.service = service
'@param name: 根节点的名称'
def remote_takeProxy(self, name, transport):
log.msg(('node [%s] takeProxy ready' % name)) child = Child(name) self.childsmanager.addChild(child) child.setTransport(transport) self.doChildConnect(name, transport)
'圓node节点连接时的倄理'
def doChildConnect(self, name, transport):
pass
'@param commandId: int 指什号 @param data: str 调甚参数'
def remote_callTarget(self, command, *args, **kw):
data = self.service.callTarget(command, *args, **kw) return data
''
def dropChild(self, *args, **kw):
self.childsmanager.dropChild(*args, **kw)
''
def dropChildByID(self, childId):
self.doChildLostConnect(childId) self.childsmanager.dropChildByID(childId)
''
def dropChildSessionId(self, session_id):
child = self.childsmanager.getChildBYSessionId(session_id) if (not child): return childname = child.getName() self.doChildLostConnect(childname) self.childsmanager.dropChildByID(childname)
'圓node节点连接时的倄理'
def doChildLostConnect(self, childname):
pass