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
|
Subsets and Splits