rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
patch_socket(dns=dns)
patch_socket(dns=dns, aggressive=aggressive)
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, aggressive=False): # order is important if os: patch_os() if time: patch_time() if thread: patch_thread() if socket: patch_socket(dns=dns) if select: patch_select(aggressive=aggressive) if ssl: patch_ssl()
def patch_thread():
def patch_thread(threading=True, _threading_local=True): """Patch the standard :mod:`thread` module to make it greenlet-based. Patch the following names in :mod:`thread` module: - :func:`get_ident` - :func:`start_new_thread` - :class:`LockType` - :func:`allocate_lock` - :func:`exit` - :func:`stack_size` - :class:`_loc...
def patch_thread(): from gevent import thread as green_thread thread = __import__('thread') if thread.exit is not green_thread.exit: thread.get_ident = green_thread.get_ident thread.start_new_thread = green_thread.start_new_thread thread.LockType = green_thread.LockType thread.allocate_lock = green_thread.allocate_lock...
if noisy and 'threading' in sys.modules: sys.stderr.write("gevent.monkey's warning: 'threading' is already imported\n\n") if '_threading_local' not in sys.modules: import _threading_local thread._local = _threading_local.local elif noisy: sys.stderr.write("gevent.monkey's warning: '_threading_local' is already importe...
from gevent.local import local thread._local = local if threading: if noisy and 'threading' in sys.modules: sys.stderr.write("gevent.monkey's warning: 'threading' is already imported\n\n") threading = __import__('threading') threading.local = local if _threading_local: _threading_local = __import__('_threading_local') ...
def patch_thread(): from gevent import thread as green_thread thread = __import__('thread') if thread.exit is not green_thread.exit: thread.get_ident = green_thread.get_ident thread.start_new_thread = green_thread.start_new_thread thread.LockType = green_thread.LockType thread.allocate_lock = green_thread.allocate_lock...
if (self.wsgi_input.position < int(self.environ.get('CONTENT_LENGTH', 0)) or self.wsgi_input.chunked_input): self.wsgi_input.read()
self.wsgi_input._discard()
def handle_one_response(self): self.time_start = time.time() self.status = None self.headers_sent = False
return iter(self.read())
while 1: line = self.readline() if not line: break yield line
def __iter__(self): return iter(self.read())
except socket.error, e: if 'ECONNREFUSED' not in str(e):
except socket.error, ex: if ex[0] != errno.ECONNREFUSED:
def check_refused(self): try: self.connect() except socket.error, e: if 'ECONNREFUSED' not in str(e): raise except IOError, e: print 'WARNING: instead of ECONNREFUSED got IOError: %s' % e
pass def tearDown(self): pass def application(self, environ, start_response): start_response('200 OK', {}) return [environ['wsgi.input'].read()] def test_012_ssl_server(self):
def setUp(self): pass
sock = socket.ssl_listener(('', 4201), private_key_file, certificate_file) g = gevent.spawn(self.get_wsgi_module().server, sock, validator(self.application)) try: req = HTTPRequest("https://localhost:4201/foo", method="POST", data='abc') f = urllib2.urlopen(req) result = f.read() self.assertEquals(result, 'abc') final...
sock = socket.socket() socket.bind_and_listen(sock, ('', 4201)) self.sock = socket.ssl(sock, private_key_file, certificate_file) self.g = gevent.spawn(self.get_wsgi_module().server, self.sock, validator(self.application)) def tearDown(self): self.g.kill(block=True) def urlopen(self, *args, **kwargs): req = HTTPReque...
def test_012_ssl_server(self): certificate_file = os.path.join(os.path.dirname(__file__), 'test_server.crt') private_key_file = os.path.join(os.path.dirname(__file__), 'test_server.key')
certificate_file = os.path.join(os.path.dirname(__file__), 'test_server.crt') private_key_file = os.path.join(os.path.dirname(__file__), 'test_server.key') sock = socket.ssl_listener(('', 4202), private_key_file, certificate_file) g = gevent.spawn(self.get_wsgi_module().server, sock, validator(self.application)) try: r...
result = self.urlopen().read() self.assertEquals(result, '')
def test_013_empty_return(self): certificate_file = os.path.join(os.path.dirname(__file__), 'test_server.crt') private_key_file = os.path.join(os.path.dirname(__file__), 'test_server.key') sock = socket.ssl_listener(('', 4202), private_key_file, certificate_file) g = gevent.spawn(self.get_wsgi_module().server, sock, va...
if failed: print 'FAILURES: ' print ' - ' + '\n - '.join(failed) if timedout: print 'TIMEOUTS: ' print ' - ' + '\n - '.join(timedout)
def print_stats(options): db = sqlite3.connect(options.db) cursor = db.cursor() if options.runid is None: options.runid = cursor.execute('select runid from test order by started_at desc limit 1').fetchall()[0][0] print 'Using the latest runid: %s' % options.runid total = len(get_testcases(cursor, options.runid)) failed...
s.killone(p1)
s.killone(p1, block=False)
def check(count1, count2): assert p1, p1 assert p2, p2 assert not p1.dead, p1 assert not p2.dead, p2 self.assertEqual(u1.shot_count, count1) self.assertEqual(u2.shot_count, count2)
s.kill() s.kill() s.kill()
s.kill(block=False) s.kill(block=False) s.kill(block=False)
def check(count1, count2): assert p1, p1 assert p2, p2 assert not p1.dead, p1 assert not p2.dead, p2 self.assertEqual(u1.shot_count, count1) self.assertEqual(u2.shot_count, count2)
wait_read(self._sock.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout, event=self._read_event)
def accept(self): while True: try: client_socket, address = self._sock.accept() break except error, ex: if ex[0] != errno.EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() wait_read(self._sock.fileno(), timeout=self.timeout) return socket(_sock=client_socket), address
wait_read(self.fileno(), timeout=self.timeout)
wait_read(self.fileno(), timeout=self.timeout, event=self._read_event)
def recv(self, *args): while True: try: res = self._sock.recv(*args) #print 'received: %r' % (res, ) return res except error, ex: if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise # QQQ without clearing exc_info test__refcount.test_clean_exit fails sys.exc_clear() wait_read(self.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout, event=self._read_event)
def recvfrom(self, *args): while True: try: return self._sock.recvfrom(*args) except error, ex: if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() wait_read(self._sock.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout, event=self._read_event)
def recvfrom_into(self, *args): while True: try: return self._sock.recvfrom_into(*args) except error, ex: if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() wait_read(self._sock.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout)
wait_read(self._sock.fileno(), timeout=self.timeout, event=self._read_event)
def recv_into(self, *args): while True: try: return self._sock.recv_into(*args) except error, ex: if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() wait_read(self._sock.fileno(), timeout=self.timeout)
wait_write(self._sock.fileno(), timeout=timeout)
wait_write(self._sock.fileno(), timeout=timeout, event=self._write_event)
def send(self, data, flags=0, timeout=timeout_default): #print 'sending: %r' % data if timeout is timeout_default: timeout = self.timeout try: return self._sock.send(data, flags) except error, ex: if ex[0] != EWOULDBLOCK or timeout == 0.0: raise sys.exc_clear() wait_write(self._sock.fileno(), timeout=timeout) try: retu...
wait_write(self.fileno(), timeout=self.timeout)
wait_write(self.fileno(), timeout=self.timeout, event=self._write_event)
def sendto(self, *args): try: return self._sock.sendto(*args) except error, ex: if ex[0] != EWOULDBLOCK or timeout == 0.0: raise sys.exc_clear() wait_write(self.fileno(), timeout=self.timeout) try: return self._sock.sendto(*args) except error, ex2: if ex2[0] == EWOULDBLOCK: return 0 raise
self.assertEqual(hexobj.sub('X', str(g)), '<Greenlet at X: <bound method A.method of <__main__.A object at X>>>')
str_g = hexobj.sub('X', str(g)) str_g = str_g.replace(__name__, 'module') self.assertEqual(str_g, '<Greenlet at X: <bound method A.method of <module.A object at X>>>')
def test_method(self): g = gevent.Greenlet.spawn(A().method) self.assertEqual(hexobj.sub('X', str(g)), '<Greenlet at X: <bound method A.method of <__main__.A object at X>>>') assert_not_ready(g) g.join() assert_ready(g) self.assertEqual(hexobj.sub('X', str(g)), '<Greenlet at X: <bound method A.method of <__main__.A obj...
"""A bounded semaphore checks to make sure its current value doesn’t exceed its initial value.
"""A bounded semaphore checks to make sure its current value doesn't exceed its initial value.
def __exit__(self, typ, val, tb): self.release()
with limited capacity. If the semaphore is released too many times it’s a sign of a bug.
with limited capacity. If the semaphore is released too many times it's a sign of a bug.
def __exit__(self, typ, val, tb): self.release()
raise TypeError('Expected a regular socket, not SSLObject: %r' % (listener, ))
raise TypeError('Expected a regular socket, not SSLSocket: %r' % (listener, ))
def set_listener(self, listener, backlog=None): if hasattr(listener, 'accept'): if hasattr(listener, 'do_handshake'): raise TypeError('Expected a regular socket, not SSLObject: %r' % (listener, )) if backlog is not None: raise TypeError('backlog must be None when a socket instance is passed') self.address = listener.ge...
if self.spawn: self.http = http.HTTPServer(self.handle) else: self.http = MainLoopServer(self.handle) s = self.http.start((self.address, 0)) self.port = s.getsockname()[1]
self.server = http.HTTPServer(self.address, self.handle) self.server.start()
def setUp(self): if self.spawn: self.http = http.HTTPServer(self.handle) else: self.http = MainLoopServer(self.handle) s = self.http.start((self.address, 0)) self.port = s.getsockname()[1]
self.http.stop()
self.server.stop()
def tearDown(self): #self.print_netstat('before stop') timeout = gevent.Timeout.start_new(0.1) try: self.http.stop() finally: timeout.cancel() #self.print_netstat('after stop') self.check_refused()
cmd ='sudo netstat -anp | grep %s' % self.port
cmd ='sudo netstat -anp | grep %s' % self.server.server_port
def print_netstat(self, comment=''): cmd ='sudo netstat -anp | grep %s' % self.port print cmd, ' # %s' % comment os.system(cmd)
return 'http://%s:%s' % (self.address, self.port)
return 'http://%s:%s' % (self.server.server_host, self.server.server_port)
def url(self): return 'http://%s:%s' % (self.address, self.port)
s.connect((self.address, self.port))
s.connect((self.server.server_host, self.server.server_port))
def connect(self): s = socket.socket() s.connect((self.address, self.port)) return s
spawn = True
def check_refused(self): try: self.connect() except socket.error, ex: if ex[0] != errno.ECONNREFUSED: raise except IOError, e: print 'WARNING: instead of ECONNREFUSED got IOError: %s' % e
self.http.stop()
self.server.stop()
def test(self): s = self.connect() s.sendall('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') s.sendall('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') s.close() self.http.stop() gevent.sleep(0.02) # stopping what already stopped is OK self.http.stop()
class TestSendReplySpawn(TestSendReply): spawn = True
def test_keepalive(self): s = self.connect() s.sendall('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') s.sendall('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
response = urlopen(self.url)
urlopen(self.url)
def test(self): try: response = urlopen(self.url) except HTTPError, e: assert e.code == 500, e assert e.msg == 'Internal Server Error', e
class TestExceptionSpawn(TestException): spawn = True
def test(self): try: response = urlopen(self.url) except HTTPError, e: assert e.code == 500, e assert e.msg == 'Internal Server Error', e
spawn = True
def test(self): try: response = urlopen(self.url) except HTTPError, e: assert e.code == 500, e assert e.msg == 'Internal Server Error', e
spawn = False
def test_client_closes_11(self): s = self.connect() s.sendall('GET / HTTP/1.1\r\n\r\n') s.close() gevent.sleep(0.02)
response = urlopen(self.url) except Exception, ex: assert str(ex) == 'test done', ex
try: urlopen(self.url) except Exception, ex: assert str(ex) == 'test done', ex
def test(self): self.current = gevent.getcurrent() try: response = urlopen(self.url) except Exception, ex: assert str(ex) == 'test done', ex finally: self.current = None assert self.handled
result = self.pool.map_async(gevent.sleep, [0.1 for i in range(1000)])
result = self.pool.map_async(gevent.sleep, [0.1] * 1000)
def test_terminate(self): result = self.pool.map_async(gevent.sleep, [0.1 for i in range(1000)]) kill = TimingWrapper(self.pool.kill) kill(block=True) assert kill.elapsed < 0.5, kill.elapsed
_socket.socket = socket _socket.fromfd = fromfd _socket.socketpair = socketpair _socket.SocketType = SocketType
_socket.socket = socket.socket _socket.SocketType = socket.SocketType if hasattr(socket, 'socketpair'): _socket.socketpair = socket.socketpair if hasattr(socket, 'fromfd'): _socket.fromfd = socket.fromfd
def patch_socket(dns=True, aggressive=True): from gevent.socket import socket, fromfd, socketpair, SocketType _socket = __import__('socket') _socket.socket = socket _socket.fromfd = fromfd _socket.socketpair = socketpair _socket.SocketType = SocketType try: from gevent.socket import ssl, sslerror _socket.ssl = ssl _soc...
self.assertRaises(ConnectionClosed, read_http, fd) fd.close()
try: result = fd.readline() assert not result, 'The remote side is expected to close the connection, but it send %r' % (result, ) except socket.error, ex: if ex[0] not in CONN_ABORTED_ERRORS: raise
def test_004_connection_close(self): fd = self.connect().makefile(bufsize=1) fd.write('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') read_http(fd) fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') read_http(fd) fd.write('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') self.assertRaises(ConnectionClos...
hexobj = re.compile('0x[0123456789abcdef]+L?')
hexobj = re.compile('-?0x[0123456789abcdef]+L?')
def method(self): pass
return _Semaphore.release(self)
return Semaphore.release(self)
def release(self): if self.counter >= self._initial_value: raise ValueError, "Semaphore released too many times" return _Semaphore.release(self)
def patch_select():
def patch_select(aggressive=False):
def patch_select(): from gevent.select import select _select = __import__('select') globals()['_select_select'] = _select.select _select.select = select
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True):
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, aggressive=False):
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True): # order is important if os: patch_os() if time: patch_time() if thread: patch_thread() if socket: patch_socket(dns=dns) if select: patch_select() if ssl: patch_ssl()
patch_select()
patch_select(aggressive=aggressive)
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True): # order is important if os: patch_os() if time: patch_time() if thread: patch_thread() if socket: patch_socket(dns=dns) if select: patch_select() if ssl: patch_ssl()
__all__.remove('socketpair')
__implements__.remove('socketpair')
def socketpair(*args): one, two = _socket.socketpair(*args) return socket(_sock=one), socket(_sock=two)
__all__.remove('fromfd')
__implements__.remove('fromfd')
def fromfd(*args): return socket(_sock=_socket.fromfd(*args))
if not greenlet.successful():
if greenlet.exception is not None:
def join(self, timeout=None, raise_error=False): if raise_error: greenlets = self.greenlets.copy() self._empty_event.wait(timeout=timeout) for greenlet in greenlets: if not greenlet.successful(): raise greenlet.exception else: self._empty_event.wait(timeout=timeout)
for greenlet in self.greenlets:
for greenlet in list(self.greenlets):
def kill(self, exception=GreenletExit, block=True, timeout=None): timer = Timeout.start_new(timeout) try: while self.greenlets: for greenlet in self.greenlets: if greenlet not in self.dying: greenlet.kill(exception) self.dying.add(greenlet) if not block: break joinall(self.greenlets) finally: timer.cancel()
http.HTTPServer(callback).serve_forever(('0.0.0.0', 8088))
http.HTTPServer(('0.0.0.0', 8088), callback).serve_forever()
def callback(request): print request if request.uri == '/': request.add_output_header('Content-Type', 'text/html') request.send_reply(200, "OK", '<b>hello world</b>') else: request.add_output_header('Content-Type', 'text/html') request.send_reply(404, "Not Found", "<h1>Not Found</h1>")
def _chunked_read(self, rfile, length=None):
def _chunked_read(self, rfile, length=None, use_readline=False):
def _chunked_read(self, rfile, length=None): if self.wfile is not None: ## 100 Continue self.wfile.write(self.wfile_line) self.wfile = None self.wfile_line = None
if length is None: if self.chunk_length > self.position: response.append(rfile.read(self.chunk_length - self.position)) while self.chunk_length != 0: self.chunk_length = int(rfile.readline(), 16) response.append(rfile.read(self.chunk_length)) rfile.readline() else: while length > 0 and self.chunk_length != 0: if self.c...
while self.chunk_length != 0: maxreadlen = self.chunk_length - self.position if length is not None and length < maxreadlen: maxreadlen = length if maxreadlen > 0: data = reader(maxreadlen) if not data: self.chunk_length = 0 raise IOError("unexpected end of file while parsing chunked data") datalen = len(data) respons...
def _chunked_read(self, rfile, length=None): if self.wfile is not None: ## 100 Continue self.wfile.write(self.wfile_line) self.wfile = None self.wfile_line = None
return self._do_read(self.rfile.readline)
if self.chunked_input: return self._chunked_read(self.rfile, size, True) else: return self._do_read(self.rfile.readline, size)
def readline(self, size=None): return self._do_read(self.rfile.readline)
if self.wsgi_input.position < self.environ.get('CONTENT_LENGTH', 0):
if (self.wsgi_input.position < int(self.environ.get('CONTENT_LENGTH', 0)) or self.wsgi_input.chunked_input):
def handle_one_response(self): self.time_start = time.time() self.status = None self.headers_sent = False
start = time.time() self.status = None
self.time_start = time.time() self.status = '-'
def handle_one_response(self): start = time.time() self.status = None self.headers_sent = False
finish = time.time() if self.status is not None: status = self.status.split()[0] else: status = '-' self.server.log_message('%s - - [%s] "%s" %s %s %.6f' % ( self.client_address[0], self.log_date_time_string(), self.requestline, status, self.response_length, finish - start))
self.time_finish = time.time() self.log_request()
def handle_one_response(self): start = time.time() self.status = None self.headers_sent = False
self.assertEqual(str(waiter), "<Waiter greenlet=None exc_info=(<type 'exceptions.ZeroDivisionError'>,)>")
assert re.match('^<Waiter greenlet=None exc_info=.*ZeroDivisionError.*$', str(waiter)), str(waiter)
def test(self): waiter = self.waiter self.assertEqual(str(waiter), '<Waiter greenlet=None>') waiter.switch(25) self.assertEqual(str(waiter), '<Waiter greenlet=None value=25>') self.assertEqual(waiter.get(), 25)
assert str(waiter).startswith('<Waiter greenlet=<Greenlet at 0x'), str(waiter)
assert str(waiter).startswith('<Waiter greenlet=<Greenlet at '), str(waiter)
def test(self): waiter = self.waiter self.assertEqual(str(waiter), '<Waiter greenlet=None>') waiter.switch(25) self.assertEqual(str(waiter), '<Waiter greenlet=None value=25>') self.assertEqual(waiter.get(), 25)
__all__.remove('gethostbyname') __all__.remove('getaddrinfo')
__implements__.remove('gethostbyname') __implements__.remove('getaddrinfo')
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket...
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, aggressive=False):
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, aggressive=True):
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, aggressive=False): # order is important if os: patch_os() if time: patch_time() if thread: patch_thread() if socket: patch_socket(dns=dns, aggressive=aggressive) if select: patch_select(aggressive=aggressive) if ssl: patch_ssl(...
if backlog is None: backlog = self.backlog
if backlog is not None: self.backlog = backlog
def __init__(self, listener, backlog=None, pool=None, log=sys.stderr, **ssl_args): self.ssl_enabled = False if hasattr(listener, 'accept'): self.socket = listener self.address = listener.getsockname() self.ssl_enabled = hasattr(listener, 'do_handshake') else: if not isinstance(listener, tuple): raise TypeError('Expecte...
data = ''
etc_hosts = ''
def test_25(self): self._test(25)
towrite.append('%s %s\r\n' % (self.protocol_version, self.status))
towrite.append('%s %s\r\n' % (self.request_version, self.status))
def write(self, data): towrite = [] if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: self.headers_sent = True towrite.append('%s %s\r\n' % (self.protocol_version, self.status)) for header in self.response_headers: towrite.append('%s: %s\r\n' % header)
env[key] += ',' + value
if 'COOKIE' in key: env[key] += '; ' + value else: env[key] += ',' + value
def get_environ(self): env = self.server.get_environ() env['REQUEST_METHOD'] = self.command env['SCRIPT_NAME'] = ''
return socket(_sock=self._sock)
new_sock = socket(_sock=self._sock) new_sock.timeout = self.timeout return new_sock
def dup(self): """dup() -> socket object
raise TypeError("Must be int or have file() method: %r" % (obj, ))
raise TypeError("Must be int or have fileno() method: %r" % (obj, ))
def get_fileno(obj): try: f = obj.fileno except AttributeError: if not isinstance(obj, int): raise TypeError("Must be int or have file() method: %r" % (obj, )) return obj else: return f()
hexobj = re.compile('-?0x[0123456789abcdef]+L?')
hexobj = re.compile('-?0x[0123456789abcdef]+L?', re.I)
def method(self): pass
args = (type(self).__name__, self._testMethodName, self._event_count, event_count)
args = (type(self).__name__, self.testname, self._event_count, event_count)
def tearDown(self): if hasattr(self, '_timer'): self._timer.cancel() hub = gevent.hub.get_hub() if self._switch_count is not None and hasattr(hub, 'switch_count'): msg = '' if hub.switch_count < self._switch_count: msg = 'hub.switch_count decreased?\n' elif hub.switch_count == self._switch_count: if self.switch_expecte...
elif arg == '--static': static = True elif arg == '--dynamic': static = False
def add_library_dir(path, must_exist=True): if path not in library_dirs: check_dir(path, must_exist) library_dirs.append(path)
if static:
if sys.platform == 'win32':
def add_library_dir(path, must_exist=True): if path not in library_dirs: check_dir(path, must_exist) library_dirs.append(path)
libevent_sources = ['event.c', 'buffer.c', 'evbuffer.c', 'event_tagging.c', 'evutil.c', 'log.c', 'signal.c', 'evdns.c', 'http.c', 'strlcpy.c'] if sys.platform == 'win32': libraries = ['wsock32', 'advapi32'] include_dirs.extend([ join(libevent_source_path, 'WIN32-Code'), join(libevent_source_path, 'compat') ]) libevent_...
extra_compile_args += ['-DWIN32'] libraries = ['wsock32', 'advapi32', 'ws2_32', 'shell32'] include_dirs.extend([ join(libevent_source_path, 'WIN32-Code'), join(libevent_source_path, 'compat') ]) libevent_sources = [join(libevent_source_path, filename) for filename in libevent_sources] libevent_sources = [filename for f...
def add_library_dir(path, must_exist=True): if path not in library_dirs: check_dir(path, must_exist) library_dirs.append(path)
sources.append( join(libevent_source_path, filename) )
sources.append(filename)
def add_library_dir(path, must_exist=True): if path not in library_dirs: check_dir(path, must_exist) library_dirs.append(path)
CONNECT_ERR = (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK) CONNECT_SUCCESS = (0, errno.EISCONN) if sys.platform == 'win32': CONNECT_ERR += (errno.WSAEINVAL, ) def socket_connect(descriptor, address): err = descriptor.connect_ex(address) if err in CONNECT_ERR: return None if err not in CONNECT_SUCCESS: raise...
def close(self): try: if self._sock: self.flush() finally: if self._close: self._sock.close() self._sock = None
fd = self.fd
sock = self.fd
def connect(self, address): if isinstance(address, tuple) and len(address)==2: address = gethostbyname(address[0]), address[1] if self.timeout == 0.0: return self.fd.connect(address) fd = self.fd if self.timeout is None: while not socket_connect(fd, address): wait_write(fd.fileno()) else: end = time.time() + self.timeo...
while not socket_connect(fd, address): wait_write(fd.fileno())
while True: err = sock.getsockopt(SOL_SOCKET, SO_ERROR) if err: raise error(err, strerror(err)) result = sock.connect_ex(address) if not result or result == EISCONN: break elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows): wait_readwrite(sock.fileno()) else: raise error(result, ...
def connect(self, address): if isinstance(address, tuple) and len(address)==2: address = gethostbyname(address[0]), address[1] if self.timeout == 0.0: return self.fd.connect(address) fd = self.fd if self.timeout is None: while not socket_connect(fd, address): wait_write(fd.fileno()) else: end = time.time() + self.timeo...
if socket_connect(fd, address): return if time.time() >= end: raise timeout wait_write(fd.fileno(), timeout=end-time.time())
err = sock.getsockopt(SOL_SOCKET, SO_ERROR) if err: raise error(err, strerror(err)) result = sock.connect_ex(address) if not result or result == EISCONN: break elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows): timeleft = end - time.time() if timeleft <= 0: raise timeout wait_re...
def connect(self, address): if isinstance(address, tuple) and len(address)==2: address = gethostbyname(address[0]), address[1] if self.timeout == 0.0: return self.fd.connect(address) fd = self.fd if self.timeout is None: while not socket_connect(fd, address): wait_write(fd.fileno()) else: end = time.time() + self.timeo...
if isinstance(address, tuple) and len(address)==2: address = gethostbyname(address[0]), address[1] if self.timeout == 0.0: return self.fd.connect_ex(address) fd = self.fd if self.timeout is None: while not socket_connect(fd, address): try: wait_write(fd.fileno()) except error, ex: return ex[0] else: end = time.time() +...
try: return self.connect(address) or 0 except timeout: return EAGAIN except error, ex: if type(ex) is error: return ex[0] else: raise
def connect_ex(self, address): if isinstance(address, tuple) and len(address)==2: address = gethostbyname(address[0]), address[1] if self.timeout == 0.0: return self.fd.connect_ex(address) fd = self.fd if self.timeout is None: while not socket_connect(fd, address): try: wait_write(fd.fileno()) except error, ex: return ...
gevent.sleep(0.1) fileobj = socket.create_connection(('127.0.0.1', 7891)).makefile() while True: line = gevent.with_timeout(0.1, fileobj.readline, timeout_value=None) if line is None: break fileobj.write('2+2\r\n') fileobj.flush() line = fileobj.readline()
gevent.sleep(0) conn = socket.create_connection(('127.0.0.1', 7891)) read_until(conn, '>>> ') conn.sendall('2+2\r\n') line = conn.makefile().readline()
def test(self): server = backdoor.BackdoorServer.spawn(('127.0.0.1', 7891)) gevent.sleep(0.1) fileobj = socket.create_connection(('127.0.0.1', 7891)).makefile() while True: line = gevent.with_timeout(0.1, fileobj.readline, timeout_value=None) if line is None: break fileobj.write('2+2\r\n') fileobj.flush() line = fileob...
opts=0, rcnum=0, xmsiz=0, dfunit=0):
opts=0, rcnum=0, xmsiz=67108864, dfunit=0):
def open(self, path, omode=OWRITER|OCREAT, bnum=0, apow=-1, fpow=-1, opts=0, rcnum=0, xmsiz=0, dfunit=0): """Open a database file and connect a hash database object.""" if rcnum: self.setcache(rcnum) if xmsiz: self.setxmsiz(xmsiz) if dfunit: self.setdfunit(dfunit) if bnum or apow >= 0 or fpow >= 0 or opts: self.tune(bn...
if xmsiz:
if xmsiz != 67108864:
def open(self, path, omode=OWRITER|OCREAT, bnum=0, apow=-1, fpow=-1, opts=0, rcnum=0, xmsiz=0, dfunit=0): """Open a database file and connect a hash database object.""" if rcnum: self.setcache(rcnum) if xmsiz: self.setxmsiz(xmsiz) if dfunit: self.setdfunit(dfunit) if bnum or apow >= 0 or fpow >= 0 or opts: self.tune(bn...
if bnum or apow >= 0 or fpow >= 0 or opts: self.tune(bnum, apow, fpow, opts)
def open(self, path, omode=OWRITER|OCREAT, bnum=0, apow=-1, fpow=-1, opts=0, rcnum=0, xmsiz=0, dfunit=0): """Open a database file and connect a hash database object.""" if rcnum: self.setcache(rcnum) if xmsiz: self.setxmsiz(xmsiz) if dfunit: self.setdfunit(dfunit) if bnum or apow >= 0 or fpow >= 0 or opts: self.tune(bn...
def fwmkeys(self, prefix):
def fwmkeys(self, prefix, max_=-1):
def fwmkeys(self, prefix): """Get forward matching string keys in a hash database object.""" tclist_objs = tc.hdb_fwmkeys2(self.db, prefix) if not tclist_objs: raise tc.TCException(tc.hdb_errmsg(tc.hdb_ecode(self.db))) return util.deserialize_tclist(tclist_objs, str)
tclist_objs = tc.hdb_fwmkeys2(self.db, prefix)
tclist_objs = tc.hdb_fwmkeys2(self.db, prefix, max_)
def fwmkeys(self, prefix): """Get forward matching string keys in a hash database object.""" tclist_objs = tc.hdb_fwmkeys2(self.db, prefix) if not tclist_objs: raise tc.TCException(tc.hdb_errmsg(tc.hdb_ecode(self.db))) return util.deserialize_tclist(tclist_objs, str)
def fwmkeys(self, prefix, as_raw=True):
def fwmkeys(self, prefix, max_=-1, as_raw=True):
def fwmkeys(self, prefix, as_raw=True): """Get forward matching string keys in a hash database object.""" (c_prefix, c_prefix_len) = util.serialize(prefix, as_raw) tclist_objs = tc.hdb_fwmkeys(self.db, c_prefix, c_prefix_len) if not tclist_objs: raise tc.TCException(tc.hdb_errmsg(tc.hdb_ecode(self.db))) as_type = util....
tclist_objs = tc.hdb_fwmkeys(self.db, c_prefix, c_prefix_len)
tclist_objs = tc.hdb_fwmkeys(self.db, c_prefix, c_prefix_len, max_)
def fwmkeys(self, prefix, as_raw=True): """Get forward matching string keys in a hash database object.""" (c_prefix, c_prefix_len) = util.serialize(prefix, as_raw) tclist_objs = tc.hdb_fwmkeys(self.db, c_prefix, c_prefix_len) if not tclist_objs: raise tc.TCException(tc.hdb_errmsg(tc.hdb_ecode(self.db))) as_type = util....
('opts', c_uint8, 1))
('opts', c_uint8, 1, 0))
def cfunc(name, dll, result, *args): """Build and apply a ctypes prototype complete with parameter flags e.g. cvMinMaxLoc = cfunc('cvMinMaxLoc', _cxDLL, None, ('image', IplImage_p, 1), ('min_val', c_double_p, 2), ('max_val', c_double_p, 2), ('min_loc', CvPoint_p, 2), ('max_loc', CvPoint_p, 2), ('mask', IplImage_p, 1, ...
pow -- specifies the maximum number of elements of the free block pool
fpow -- specifies the maximum number of elements of the free block pool
def cfunc(name, dll, result, *args): """Build and apply a ctypes prototype complete with parameter flags e.g. cvMinMaxLoc = cfunc('cvMinMaxLoc', _cxDLL, None, ('image', IplImage_p, 1), ('min_val', c_double_p, 2), ('max_val', c_double_p, 2), ('min_loc', CvPoint_p, 2), ('max_loc', CvPoint_p, 2), ('mask', IplImage_p, 1, ...
('opts', c_uint8, 1,))
('opts', c_uint8, 1, 0))
def cfunc(name, dll, result, *args): """Build and apply a ctypes prototype complete with parameter flags e.g. cvMinMaxLoc = cfunc('cvMinMaxLoc', _cxDLL, None, ('image', IplImage_p, 1), ('min_val', c_double_p, 2), ('max_val', c_double_p, 2), ('min_loc', CvPoint_p, 2), ('max_loc', CvPoint_p, 2), ('mask', IplImage_p, 1, ...
adb_put2 = cfunc('tcadbput2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1), ('vstr', c_char_p, 1))
adb_put2 = cfunc_fast('tcadbput2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1), ('vstr', c_char_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_putkeep2 = cfunc('tcadbputkeep2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1), ('vstr', c_char_p, 1))
adb_putkeep2 = cfunc_fast('tcadbputkeep2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1), ('vstr', c_char_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_putcat2 = cfunc('tcadbputcat2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1), ('vstr', c_char_p, 1))
adb_putcat2 = cfunc_fast('tcadbputcat2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1), ('vstr', c_char_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_out2 = cfunc('tcadbput2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1))
adb_out2 = cfunc_fast('tcadbout2', libtc, c_bool, ('adb', c_void_p, 1), ('kstr', c_char_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_get2 = cfunc('tcadbget2', libtc, tc_char_p, ('adb', c_void_p, 1), ('kstr', c_char_p, 1))
adb_get2 = cfunc_fast('tcadbget2', libtc, tc_char_p, ('adb', c_void_p, 1), ('kstr', c_char_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_vsiz2 = cfunc('tcadbvsiz2', libtc, c_int, ('adb', c_void_p, 1), ('kstr', c_char_p, 1))
adb_vsiz2 = cfunc_fast('tcadbvsiz2', libtc, c_int, ('adb', c_void_p, 1), ('kstr', c_char_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_iternext2 = cfunc('tcadbiternext2', libtc, tc_char_p, ('adb', c_void_p, 1))
adb_iternext2 = cfunc_fast('tcadbiternext2', libtc, tc_char_p, ('adb', c_void_p, 1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
adb_fwmkeys2 = cfunc('tcadbfwmkeys2', libtc, TCLIST_P, ('adb', c_void_p, 1), ('pstr', c_char_p, 1), ('max', c_int, 1, -1))
adb_fwmkeys2 = cfunc_fast('tcadbfwmkeys2', libtc, TCLIST_P, ('adb', c_void_p, 1), ('pstr', c_char_p, 1), ('max', c_int, 1, -1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
(c_value, c_value_len) = serialize(key, as_raw=as_raw)
(c_value, c_value_len) = serialize(value, as_raw=as_raw)
def serialize_tcmap(dict_, as_raw=False): """Serialize a dictionary into a TCMAP object.""" tcmap = tc.tcmapnew() for key, value in dict_.iteritems(): (c_key, c_key_len) = serialize(key, as_raw=True) (c_value, c_value_len) = serialize(key, as_raw=as_raw) tc.tcmapput(tcmap, c_key, c_key_len, c_value, c_value_len) return...
if not c_key:
if not c_key_len:
def deserialize_tcmap(tcmap, schema=None): """Deserialize a TCMAP object into a dictionary.""" dict_ = {} tc.tcmapiterinit(tcmap) while True: c_key, c_key_len = tc.tcmapiternext(tcmap) if not c_key: break c_value, c_value_len = tc.tcmapiterval(c_key) key = deserialize(c_key, c_key_len, as_type=str) as_type = schema.get...
value = deserialize(c_key, c_key_len, as_type=as_type)
value = deserialize(c_value, c_value_len, as_type=as_type)
def deserialize_tcmap(tcmap, schema=None): """Deserialize a TCMAP object into a dictionary.""" dict_ = {} tc.tcmapiterinit(tcmap) while True: c_key, c_key_len = tc.tcmapiternext(tcmap) if not c_key: break c_value, c_value_len = tc.tcmapiterval(c_key) key = deserialize(c_key, c_key_len, as_type=str) as_type = schema.get...
('xmsiz', c_int64, 1, 0))
('xmsiz', c_int64, 1, 67108864))
def __del__(self): if self and libtc: libtc.tcmapdel(self)
hdb_fwmkeys2 = cfunc('tchdbfwmkeys2', libtc, TCLIST_P, ('hdb', c_void_p, 1), ('pstr', c_char_p, 1), ('max', c_int, 1, -1))
hdb_fwmkeys2 = cfunc_fast('tchdbfwmkeys2', libtc, TCLIST_P, ('hdb', c_void_p, 1), ('pstr', c_char_p, 1), ('max', c_int, 1, -1))
def __del__(self): if self and libtc: libtc.tcmapdel(self)