本文整理匯總了Python中uvloop.EventLoopPolicy方法的典型用法代碼示例。如果您正苦於以下問題:Python uvloop.EventLoopPolicy方法的具體用法?Python uvloop.EventLoopPolicy怎麽用?Python uvloop.EventLoopPolicy使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類uvloop
的用法示例。
在下文中一共展示了uvloop.EventLoopPolicy方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def main():
args = parse_args()
if args.uvloop:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
task = loop.create_task(Benchmark(args).bench_simple())
task.add_done_callback(lambda _, loop=loop: loop.stop())
def signal_hndl(_task=task):
_task.cancel()
loop.add_signal_handler(signal.SIGTERM, signal_hndl)
loop.add_signal_handler(signal.SIGINT, signal_hndl)
try:
loop.run_forever()
finally:
loop.close()
if not task.cancelled():
task.result()
示例2: uvloop_worker
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def uvloop_worker(
config: Config, sockets: Optional[Sockets] = None, shutdown_event: Optional[EventType] = None
) -> None:
try:
import uvloop
except ImportError as error:
raise Exception("uvloop is not installed") from error
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
app = load_application(config.application_path)
shutdown_trigger = None
if shutdown_event is not None:
shutdown_trigger = partial(check_multiprocess_shutdown_event, shutdown_event, asyncio.sleep)
_run(
partial(worker_serve, app, config, sockets=sockets),
debug=config.debug,
shutdown_trigger=shutdown_trigger,
)
示例3: test_it_logs_messages
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def test_it_logs_messages(self):
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
async def test():
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader)
transport, _ = await loop.connect_read_pipe(
lambda: protocol, self.read_pipe
)
logger = Logger.with_default_handlers()
await logger.info("Xablau")
logged_content = await reader.readline()
self.assertEqual(logged_content, b"Xablau\n")
transport.close()
await logger.shutdown()
loop.run_until_complete(test())
示例4: main
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def main() -> int:
print("Hello, World!")
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
# Each client connection will create a new protocol instance
coro = loop.create_server(RedisProtocol, "127.0.0.1", 7878)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
return 0
示例5: __init__
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def __init__(self, verbosity=0, max_tasks=512):
"""Constructor.
Args:
verbosity: set output verbosity: 0 (default) is none, 3 is debug
max_tasks: the maximum number of tasks asyncio will queue (default 512)
"""
self.tasks = []
self.errors = []
self.fqdn = []
self.ignore_hosts = []
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
self.loop = asyncio.get_event_loop()
self.resolver = aiodns.DNSResolver(loop=self.loop, rotate=True)
self.sem = asyncio.BoundedSemaphore(max_tasks)
self.max_tasks = max_tasks
self.verbosity = verbosity
self.logger = ConsoleLogger(verbosity)
示例6: main
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--redis-use-sentinel', action='store_true')
parser.add_argument('--sentinels', type=str)
parser.add_argument('--redis-host', type=str, default='localhost')
parser.add_argument('--no-uvloop', action='store_true')
parser.add_argument('--host', type=str, default='localhost')
parser.add_argument('--port', type=int, default=8080)
args = parser.parse_args()
app = web.Application()
app[REDIS] = {
SENTINEL: args.redis_use_sentinel,
SENTINELS: args.sentinels,
HOST: args.redis_host
}
app.on_startup.append(initialize_client_session)
app.on_startup.append(initialize_keystore)
app.on_cleanup.append(close_keystore)
app.on_cleanup.append(close_client_session_connection)
app.router.add_routes(routes)
if not args.no_uvloop:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
web.run_app(app, host=args.host, port=args.port)
示例7: __init__
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except:
pass
self.__started = False
self.__tasks = {}
self.__procs = {}
self.loop = asyncio.get_event_loop()
示例8: pytest_configure
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def pytest_configure(config):
bins = config.getoption('--redis-server')[:]
cmd = 'which redis-server'
if not bins:
with os.popen(cmd) as pipe:
path = pipe.read().rstrip()
assert path, (
"There is no redis-server on your computer."
" Please install it first")
REDIS_SERVERS[:] = [path]
else:
REDIS_SERVERS[:] = bins
VERSIONS.update({srv: _read_server_version(srv)
for srv in REDIS_SERVERS})
assert VERSIONS, ("Expected to detect redis versions", REDIS_SERVERS)
class DynamicFixturePlugin:
@pytest.fixture(scope='session',
params=REDIS_SERVERS,
ids=format_version)
def server_bin(self, request):
"""Common for start_server and start_sentinel
server bin path parameter.
"""
return request.param
config.pluginmanager.register(DynamicFixturePlugin(), 'server-bin-fixture')
if config.getoption('--uvloop'):
try:
import uvloop
except ImportError:
raise RuntimeError(
"Can not import uvloop, make sure it is installed")
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
示例9: loop
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def loop() -> Generator:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
yield loop
try:
if loop and not loop.is_closed():
loop.close()
except RuntimeWarning:
pass
示例10: try_setup_uvloop
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def try_setup_uvloop():
if config.SOCKS5_HOST and config.SOCKS5_PORT:
# socks mode is not compatible with uvloop
return
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
print_err("Found uvloop, using it for optimal performance")
except ImportError:
pass
示例11: run_worker
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def run_worker(cls, cls_args, sockname):
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
with devmode.CoverageConfig.enable_coverage_if_requested():
asyncio.run(worker(cls, cls_args, sockname))
示例12: event_loop_policy
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def event_loop_policy(self):
policy = self.default('EVENT_LOOP_POLICY', None)
if policy is None:
return None
if policy == 'uvloop':
import uvloop
return uvloop.EventLoopPolicy()
raise self.Error('unknown event loop policy "{}"'.format(policy))
示例13: default_event_loop
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def default_event_loop(request=None, config=None):
if request is not None:
config = request.config
loop = config.getoption("--loop")
if loop == 'uvloop':
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
else:
loop = 'asyncio'
return loop
示例14: set_loop_policy
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def set_loop_policy():
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
示例15: enable_uvloop
# 需要導入模塊: import uvloop [as 別名]
# 或者: from uvloop import EventLoopPolicy [as 別名]
def enable_uvloop(): # pragma: no cover
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
return False
else:
return True