### Create Secure SSL/TLS Server with uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt This example demonstrates setting up a secure TCP server with SSL/TLS encryption using uvloop and asyncio. It configures an `ssl.SSLContext` with a certificate and key, then starts a server using `asyncio.start_server`. The `handle_secure_client` coroutine processes incoming secure connections. Dependencies: `asyncio`, `ssl`, `uvloop`. ```python import asyncio import ssl import uvloop async def handle_secure_client(reader, writer): data = await reader.read(1024) writer.write(data) await writer.drain() writer.close() await writer.wait_closed() async def main(): # Create SSL context ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ssl_context.load_cert_chain('ssl_cert.pem', 'ssl_key.pem') ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE # Start server with SSL server = await asyncio.start_server( handle_secure_client, '127.0.0.1', 8443, ssl=ssl_context ) print("Secure server running on port 8443") async with server: await server.serve_forever() uvloop.run(main()) ``` -------------------------------- ### Install uvloop using pip Source: https://github.com/magicstack/uvloop.git/blob/master/docs/user/index.md Installs the uvloop library from PyPI. Requires Python 3.8 or later. This command-line instruction is used for system-level installation. ```console pip install uvloop ``` -------------------------------- ### Use uvloop with Aiohttp and Gunicorn Source: https://github.com/magicstack/uvloop.git/wiki/Home This example demonstrates how to use uvloop with aiohttp and gunicorn by specifying a custom worker class. This method automatically sets up uvloop without manual policy installation. ```bash gunicorn ... --worker-class aiohttp.worker.GunicornUVLoopWebWorker ``` -------------------------------- ### Build uvloop from source Source: https://github.com/magicstack/uvloop.git/blob/master/README.rst This snippet outlines the steps to build uvloop from its source repository. It includes cloning the repository, setting up a virtual environment, installing development dependencies, and finally building and testing the project using `make`. ```bash $ git clone --recursive git@github.com:MagicStack/uvloop.git $ cd uvloop $ python3 -m venv uvloop-dev $ source uvloop-dev/bin/activate $ pip install -e .[dev] $ make $ make test ``` -------------------------------- ### Legacy uvloop Installation Method (Deprecated) Source: https://context7.com/magicstack/uvloop.git/llms.txt This snippet shows a legacy installation method for uvloop, compatible with Python 3.11 and earlier. This method is deprecated starting from Python 3.12. It simply prints a message indicating uvloop is running. Dependencies: `asyncio`, `sys`, `uvloop`. ```python import asyncio import sys import uvloop async def main(): print("Running with uvloop") await asyncio.sleep(0.1) ``` -------------------------------- ### Use uvloop with Tornado Source: https://github.com/magicstack/uvloop.git/wiki/Home This snippet illustrates how to use uvloop with the Tornado framework by installing the uvloop event policy before initializing Tornado's asyncio main loop. It ensures uvloop is used for Tornado's event handling. ```python from tornado.platform.asyncio import AsyncIOMainLoop import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) AsyncIOMainLoop().install() asyncio.get_event_loop().run_forever() ``` -------------------------------- ### Set uvloop as the asyncio event loop policy Source: https://github.com/magicstack/uvloop.git/blob/master/docs/user/index.md Configures asyncio to use uvloop's high-performance event loop by default. This is the recommended way to integrate uvloop for general use. It requires importing both 'asyncio' and 'uvloop'. ```python import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) ``` -------------------------------- ### Create and set a uvloop event loop manually Source: https://github.com/magicstack/uvloop.git/blob/master/docs/user/index.md Manually creates an instance of uvloop's event loop and sets it as the current asyncio event loop. This method offers more granular control over loop instantiation. It requires importing 'asyncio' and 'uvloop'. ```python import asyncio import uvloop loop = uvloop.new_event_loop() asyncio.set_event_loop(loop) ``` -------------------------------- ### Run asyncio application with uvloop Source: https://github.com/magicstack/uvloop.git/blob/master/README.rst This snippet demonstrates the preferred method for running an asyncio application using uvloop's `run()` helper function. It configures asyncio to use uvloop, passing along any additional arguments like `debug`. ```python import uvloop async def main(): # Main entry-point. ... uvloop.run(main()) ``` -------------------------------- ### Alternative uvloop usage for Python < 3.11 Source: https://github.com/magicstack/uvloop.git/blob/master/README.rst This snippet shows an alternative method for using uvloop with Python versions 3.11 and earlier. It conditionally uses `asyncio.Runner` for newer versions and falls back to `uvloop.install()` for older ones, ensuring compatibility. ```python import asyncio import sys import uvloop async def main(): # Main entry-point. ... if sys.version_info >= (3, 11): with asyncio.Runner(loop_factory=uvloop.new_event_loop) as runner: runner.run(main()) else: uvloop.install() asyncio.run(main()) ``` -------------------------------- ### Create Protocol-Based TCP Server with uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt This snippet demonstrates how to create a low-level protocol-based TCP server using uvloop. It implements an EchoProtocol that echoes received data back to the client. This approach avoids the overhead of streams, making it suitable for high-performance networking. Dependencies include `asyncio` and `uvloop`. ```python import asyncio import uvloop class EchoProtocol(asyncio.Protocol): def connection_made(self, transport): self.transport = transport self.peername = transport.get_extra_info('peername') print(f"Connection from {self.peername}") def data_received(self, data): # Echo data back immediately self.transport.write(data) def connection_lost(self, exc): print(f"Connection closed: {self.peername}") self.transport = None async def main(): loop = asyncio.get_running_loop() # Create server with protocol factory server = await loop.create_server( EchoProtocol, '127.0.0.1', 7777 ) addr = server.sockets[0].getsockname() print(f"Protocol server on {addr}") async with server: await server.serve_forever() uvloop.run(main()) ``` -------------------------------- ### Run asyncio code with uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt Provides a simple entry point for running coroutines using the uvloop event loop. This is the recommended method for most use cases, automatically configuring asyncio.run() to use uvloop. It accepts coroutines and optional debug mode. ```python import uvloop import asyncio async def main(): # Your async application logic print("Running with uvloop!") await asyncio.sleep(1) return "Complete" # Run with uvloop - automatically configures asyncio.run() to use uvloop result = uvloop.run(main()) # Enable debug mode result = uvloop.run(main(), debug=True) ``` -------------------------------- ### Manage File Descriptors with uvloop add_reader/add_writer Source: https://context7.com/magicstack/uvloop.git/llms.txt This code snippet illustrates low-level file descriptor monitoring using uvloop's `add_reader` and `add_writer`. It creates a socket pair for inter-process communication and sets up callbacks to handle data reception and transmission. This is useful for event-driven I/O on file descriptors. Dependencies: `asyncio`, `socket`, `uvloop`. ```python import asyncio import socket import uvloop async def main(): loop = asyncio.get_running_loop() # Create socket pair for IPC rsock, wsock = socket.socketpair() result = asyncio.Future() def reader(): data = rsock.recv(100) print(f"Received: {data}") loop.remove_reader(rsock) result.set_result(data) def writer(): wsock.send(b'Hello via file descriptors!') loop.remove_writer(wsock) try: # Register callbacks for socket events loop.add_reader(rsock, reader) loop.add_writer(wsock, writer) # Wait for communication to complete data = await result print(f"Communication complete: {data}") finally: rsock.close() wsock.close() uvloop.run(main()) ``` -------------------------------- ### Run Asyncio with uvloop for Python 3.11 and earlier Source: https://context7.com/magicstack/uvloop.git/llms.txt This snippet demonstrates how to use uvloop with asyncio, adapting to Python version differences. For Python 3.11 and earlier, it uses `asyncio.Runner` with `uvloop.new_event_loop`. For Python 3.12+, it falls back to the default asyncio behavior, as `uvloop.install()` is deprecated. ```python import asyncio import uvloop import sys async def main(): # Your main async logic here pass if sys.version_info >= (3, 11): with asyncio.Runner(loop_factory=uvloop.new_event_loop) as runner: runner.run(main()) else: # Install uvloop as default event loop policy uvloop.install() # Deprecated in 3.12+ asyncio.run(main()) ``` -------------------------------- ### Create and manage uvloop event loop manually Source: https://context7.com/magicstack/uvloop.git/llms.txt Demonstrates manual creation and management of a uvloop event loop instance. This approach is suitable for advanced scenarios where explicit control over the event loop lifecycle is required. It involves creating a new loop, setting it as the current loop, running coroutines, and ensuring the loop is closed. ```python import asyncio import uvloop # Create a new uvloop event loop instance loop = uvloop.new_event_loop() # Set it as the current event loop asyncio.set_event_loop(loop) async def task(): await asyncio.sleep(0.1) return "Task complete" try: # Run coroutine until complete result = loop.run_until_complete(task()) print(result) finally: # Clean up loop.close() ``` -------------------------------- ### Low-level socket operations with uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt Demonstrates performing low-level socket operations using the `loop.sock_*` methods provided by uvloop. This offers maximum control over socket interactions, including accepting connections, receiving data, and sending data back. It's designed for scenarios requiring fine-grained network programming. ```python import asyncio import socket import uvloop async def echo_server(loop, address): # Create and configure server socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(address) sock.listen(5) sock.setblocking(False) print(f"Server listening at {address}") with sock: while True: # Accept client connection client, addr = await loop.sock_accept(sock) print(f"Connection from {addr}") # Handle client in separate task loop.create_task(handle_client(loop, client)) async def handle_client(loop, client): client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) with client: while True: # Receive data data = await loop.sock_recv(client, 65536) if not data: break # Send data back await loop.sock_sendall(client, data) async def main(): loop = asyncio.get_running_loop() await echo_server(loop, ('127.0.0.1', 9999)) uvloop.run(main()) ``` -------------------------------- ### Implement Buffered Protocol for Zero-Copy Operations with uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt This code defines an advanced protocol using pre-allocated buffers for zero-copy I/O operations with uvloop. The `EchoBufferedProtocol` utilizes `get_buffer` to provide a pre-allocated buffer and `buffer_updated` to write received data back efficiently. This minimizes data copying for high-throughput applications. Dependencies: `asyncio`, `uvloop`. ```python import asyncio import uvloop class EchoBufferedProtocol(asyncio.BufferedProtocol): def __init__(self): # Pre-allocate buffer for zero-copy reads self.buffer = bytearray(256 * 1024) def connection_made(self, transport): self.transport = transport def get_buffer(self, sizehint): # Return pre-allocated buffer return self.buffer def buffer_updated(self, nbytes): # Write received bytes back (buffer is updated in-place) self.transport.write(self.buffer[:nbytes]) def connection_lost(self, exc): self.transport = None async def main(): loop = asyncio.get_running_loop() server = await loop.create_server( EchoBufferedProtocol, '127.0.0.1', 6666 ) async with server: await server.serve_forever() uvloop.run(main()) ``` -------------------------------- ### Perform Asynchronous Socket Client Operations with uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt This snippet showcases asynchronous client-side socket operations using uvloop. It demonstrates connecting to a remote server, sending a large chunk of data, and receiving the response. The code uses `loop.sock_connect`, `loop.sock_sendall`, and `loop.sock_recv` for non-blocking socket interactions. Handles `ConnectionRefusedError`. Dependencies: `asyncio`, `socket`, `uvloop`. ```python import asyncio import socket import uvloop async def tcp_client(): # Create non-blocking socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(False) loop = asyncio.get_running_loop() try: # Connect to server await loop.sock_connect(sock, ('127.0.0.1', 8888)) # Send data message = b'Hello, Server!' * 1000 await loop.sock_sendall(sock, message) # Receive response response = b'' while len(response) < len(message): chunk = await loop.sock_recv(sock, 4096) if not chunk: break response += chunk print(f"Received {len(response)} bytes") return response except ConnectionRefusedError: print("Connection refused") finally: sock.close() uvloop.run(tcp_client()) ``` -------------------------------- ### TCP server with asyncio streams using uvloop Source: https://context7.com/magicstack/uvloop.git/llms.txt Implements a high-level, stream-based TCP server that handles concurrent client connections efficiently using uvloop. It defines a handler for each client connection, allowing for reading data and echoing it back. The server is configured to listen on a specified address and port. ```python import asyncio import uvloop async def handle_client(reader, writer): # Get client address addr = writer.get_extra_info('peername') print(f"Connection from {addr}") try: # Read data from client data = await reader.read(1000000) if data: # Echo data back writer.write(data) await writer.drain() finally: writer.close() await writer.wait_closed() async def main(): # Start TCP server on localhost:8888 server = await asyncio.start_server( handle_client, '127.0.0.1', 8888 ) addr = server.sockets[0].getsockname() print(f"Server listening on {addr}") async with server: await server.serve_forever() uvloop.run(main()) ``` -------------------------------- ### Set uvloop as Default Event Loop Policy (Deprecated) Source: https://context7.com/magicstack/uvloop.git/llms.txt This code demonstrates how to manually set uvloop as the default event loop policy for asyncio. Note that `asyncio.set_event_loop_policy` is deprecated and `uvloop.run()` is the recommended approach for newer projects. ```python import asyncio import uvloop # Set uvloop as the default event loop policy (deprecated) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # Now all asyncio.run() calls will use uvloop async def task1(): await asyncio.sleep(0.1) return "Task 1" async def task2(): await asyncio.sleep(0.1) return "Task 2" # These will use uvloop automatically result1 = asyncio.run(task1()) result2 = asyncio.run(task2()) print(result1, result2) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.