Talk given at DomCode meetup in Utrecht (August 2014) on different frameworks to do asynchronous I/O y Python, with a strong focus on asyncio (PEP-3156).
Threading uses system threads which results in higher overhead compared to asyncio which uses asynchronous non-blocking I/O and doesn't require additional system threads. This is demonstrated through benchmark tests where threading had longer execution times than asyncio for both high numbers of task spawns and long running tasks due to the additional thread management overhead in threading.
The document discusses the future of asynchronous I/O in Python. It introduces PEP 3156 and the new asyncio module in Python 3.4 as a standard library for asynchronous I/O. It describes how asyncio (called Tulip in the presentation) provides primitives like event loops, transports, protocols and coroutines to build asynchronous applications and frameworks in a pluggable, coroutine-friendly way. It provides examples of using Tulip to run asynchronous tasks and build an echo server.
~10min dive to Python Asynchronous IO
HTML version (recommended): https://dl.dropboxusercontent.com/u/1565687/speak/Python3%20AsyncIO%20Horizon/index.html
The document provides an overview of asynchronous programming in Python. It discusses how asynchronous programming can improve performance over traditional synchronous and threaded models by keeping resources utilized continuously. It introduces key concepts like callbacks, coroutines, tasks and the event loop. It also covers popular asynchronous frameworks and modules in Python like Twisted, Tornado, gevent and asyncio. Examples are provided to demonstrate asynchronous HTTP requests and concurrent factorial tasks using the asyncio module. Overall, the document serves as an introduction to asynchronous programming in Python.
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
This document discusses Python asynchronous concurrency frameworks and their future. It compares Twisted, Tornado, Gevent, and the new asyncio module. Twisted and Tornado use callbacks while Gevent uses greenlets. asyncio aims to provide an event loop like Twisted. It also introduces coroutines, tasks, and futures. The document argues that asyncio could serve as a common event loop that existing frameworks adapt to for better interoperability in the future.
This document summarizes an introductory talk on the asyncio module in Python. It discusses the main components of asyncio including:
- The event loop which acts as an implicit scheduler, putting callbacks in a queue to be run.
- Coroutines, futures and tasks - coroutines are generator functions used for asynchronous code, futures represent values that aren't available yet, and tasks run coroutines in the background.
- Transports, protocols and streams which provide different I/O handling mechanisms like readiness and completion styles on Unix and Windows.
- The event loop architecture which involves calculating timeouts, polling for I/O, processing events and timers, and running pending callbacks in a loop.
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
This document discusses asynchronous programming concepts like non-blocking I/O, event loops, coroutines, and Python libraries that support them like Twisted, gevent, and asyncio. Coffee metaphors are used to explain blocking vs non-blocking I/O. Coroutines and generators allow functions to pause and resume while yielding to the event loop. Libraries like Twisted focus on networking protocols while gevent aims to make synchronous code asynchronous via monkey patching. asyncio is part of the Python standard library and uses yield from to support nested coroutines.
Metaprogramming and Reflection in Common LispDamien Cassou
https://github.com/DamienCassou/DSLides
Lecture given on December 8th, 2011, at the Hasso-Plattner-Institute, Potsdam, Germany.
Vert.x clustering on Docker, CoreOS and ETCDTim Nolet
This talk was held at the Vert.x Meetup Amsterdam on 30-07-2014. The subject is on how to get a Vert.X cluster running in Docker containers running on CoreOS without any manual configuration.
All you need to know about the JavaScript event loopSaša Tatar
The document discusses the JavaScript event loop and call stack. It explains that JavaScript is single-threaded with an event loop that processes tasks in the order they are received. There is a call stack that processes code synchronously, and an event queue that holds asynchronous callbacks from events like timers, promises, etc. The event loop continually checks the call stack and event queue, running tasks from the queue after the stack is empty. This allows asynchronous code to run without blocking synchronous code.
PyCon lightning talk on my Toro module for Tornadoemptysquare
With Tornado’s gen module, you can turn Python generators into full-featured coroutines, but coordination among these coroutines is difficult without mutexes, semaphores, and queues.
Toro provides to Tornado coroutines a set of locking primitives and queues analogous to those that Gevent provides to Greenlets, or that the standard library provides to threads.
The document discusses concepts related to event loops and concurrency in programming. It includes code snippets in Java showing the use of NIO selectors and channels for non-blocking I/O. Diagrams are shown illustrating reactor patterns and Vert.x modules deployed across multiple CPUs. The summary provides an overview of the main topics and techniques discussed in the technical document.
Service Discovery for Continuous Delivery with DockerTim Nolet
This talk was given at Docker Meetup Amsterdam on 10 July 2014. It describes the why, what and how we are using Docker for continuous delivery at magnetic.io and how it integrates into the platform we are building.
This document discusses Node.js architecture and how software lives in hardware. It notes that Node.js uses a single-threaded, event loop model to avoid context switching and blocking I/O. This allows high throughput for operations like HTTP requests but is not optimal for long-running computations in a single thread. The document also addresses issues like callback hell and scaling event emitters, providing solutions like using promises and external queue systems. It concludes by stating Node.js is best for I/O operations, not all problems, and event loop models have existed in other frameworks before Node.js.
This document provides an overview of the Tornado web server and summarizes its internals. It begins with an introduction to Tornado, describing it as a scalable, non-blocking web server and framework written in Python. It then outlines the main Tornado modules and discusses sockets, I/O monitoring using select, poll and epoll, and how Tornado sets up its server loop and handles requests.
Rust is a systems programming language that provides memory safety without using a garbage collector. It achieves memory safety through rules of ownership, borrowing, and lifetimes that are checked at compile time. These rules prevent common memory bugs like memory leaks, dangling pointers, and use-after-free errors that are common in C and C++.
Kotlin coroutines provide a way to write asynchronous and concurrent code using suspending functions and structured concurrency. Coroutines avoid callbacks and are lighter weight than threads. They allow suspending execution and resuming it later without blocking threads. This makes asynchronous code look synchronous and avoids issues like callback hell. Coroutines provide features like parallelism, cancellation, exception handling and context propagation to simplify concurrent programming.
This document discusses multithreaded and asynchronous programming in C# and file I/O. It covers delegates and how they allow invoking methods asynchronously on separate threads. It also discusses the Threading namespace which provides classes for creating and managing threads like Thread, ThreadStart, and Timer. The document shows examples of getting thread information, passing parameters to threads, locking for thread safety, and using the Dispatcher class to update the UI from a non-UI thread.
Bucks County Tech Meetup: node.js introductiondshkolnikov
The document provides an introduction to Node.js and JavaScript. It discusses Node.js' non-blocking I/O and event loop model. Key topics covered include the npm package manager, event emitters, asynchronous code flow using process.nextTick(), avoiding callback hell with the async module, and memory management with garbage collection in Node.js. Code examples are provided on GitHub to demonstrate various concepts hands-on.
ZeroMQ is a library for building distributed applications that provides patterns for request-reply, publish-subscribe, and pipelining between clients and services. It demonstrates using these patterns to build a hello world server and client, stock ticker publisher and subscriber, and parallel task processing pipeline. ZeroMQ supports multiple transport types and languages.
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
Charla Universidad de Valencia - http://www.uv.es/
Cátedra de Capgemini 2016/17 - http://www.uv.es/capgeminiuv/sobre_nosotros.html
Asignatura : Programación avanzada y Lenguajes de programación
Título : Paradigma FP y OOP usando técnicas avanzadas de Programación
This document provides an overview of Asynchronous I/O (ASIO) and how it can be used for network programming in C++. It discusses ASIO's implementation of the Proactor pattern and how this allows for asynchronous and non-blocking I/O. It then demonstrates how to build a simple TCP echo server using ASIO that handles multiple concurrent connections through the use of connection objects and an I/O service. It also discusses how ASIO can be used beyond just networking for other asynchronous tasks like signal handling, timers, and stream I/O.
This document discusses the Tornado web server framework. It provides an overview of Tornado, including that it is a non-blocking and scalable web server that was used by FriendFeed and is now open-sourced by Facebook. It describes Tornado's architecture, which uses an IOLoop and callbacks instead of threads to remain asynchronous and non-blocking. An example "Hello World" application in Tornado is also provided. Performance comparisons show Tornado outperforming other frameworks like Node.js and Twisted.
Tornado is a non-blocking light-weight web server and framework. There's been many introductory talks about it, and it's time to look deeper into it: not just what Tornado does, but how it does it and what can we learn from it when designing our own concurrent systems.
In this talk I go over the following topics. I cover them in two parts: first I present how to use a certain feature or approach in our applications; then, I dig into Tornado's source code to see how it really works.
- Getting Started: quickly get a simple Tornado application up and running. We'll keep digging into, changing and poking this Application for most of the talk.
- An Application Listens: what an Application is, how does Tornado start it and how does it process its requests.
- Application and IOLoop: we'll look at how the IOLoop receives the connections from the users and passes them on to the Applications.
- Scheduled Tasks: we'll see how to schedule tasks and how the IOLoop will run them.
- Generators: we'll learn to use generators to handle the responses of our asynchronous calls, and how they work with the IOLoop.
Advanced:
- Websockets: how to use them and how they work.
- IOStream: how do Tornado's non-blocking sockets work.
- Database: how to use non-blocking sockets to connect to databases.
- Process: how Tornado works with multiple processes.
I presented this talk at Europython 2012 and PyGrunn 2012.
Code examples: https://bitbucket.org/grimborg/tornado-in-depth/src/tip/examples/
Este documento presenta un resumen de las principales características de asyncio, la implementación de referencia de I/O asíncrono en Python descrita en PEP 3156. asyncio proporciona event loops, coroutines, futuros y tareas para manejar operaciones de I/O de forma asíncrona. También incluye transportes y protocolos para crear servidores y clientes TCP/IP asíncronos. El objetivo es proporcionar una implementación moderna de I/O asíncrono que funcione en todas las plataformas soportadas por Python 3.3 o
Seu primeiro loop com Python AsyncIO - TDC 2016Carlos Maniero
The document discusses asynchronous programming in Python using asyncio. It begins with motivational quotes about asynchronous programming. It then provides examples of using coroutines, tasks/futures, and event loops in asyncio. It demonstrates how asyncio avoids blocking the event loop by executing slow functions in a thread pool. The document concludes by mentioning ThreadPoolExecutor and aioHTTP as topics to explore next.
This document summarizes an introductory talk on the asyncio module in Python. It discusses the main components of asyncio including:
- The event loop which acts as an implicit scheduler, putting callbacks in a queue to be run.
- Coroutines, futures and tasks - coroutines are generator functions used for asynchronous code, futures represent values that aren't available yet, and tasks run coroutines in the background.
- Transports, protocols and streams which provide different I/O handling mechanisms like readiness and completion styles on Unix and Windows.
- The event loop architecture which involves calculating timeouts, polling for I/O, processing events and timers, and running pending callbacks in a loop.
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
This document discusses asynchronous programming concepts like non-blocking I/O, event loops, coroutines, and Python libraries that support them like Twisted, gevent, and asyncio. Coffee metaphors are used to explain blocking vs non-blocking I/O. Coroutines and generators allow functions to pause and resume while yielding to the event loop. Libraries like Twisted focus on networking protocols while gevent aims to make synchronous code asynchronous via monkey patching. asyncio is part of the Python standard library and uses yield from to support nested coroutines.
Metaprogramming and Reflection in Common LispDamien Cassou
https://github.com/DamienCassou/DSLides
Lecture given on December 8th, 2011, at the Hasso-Plattner-Institute, Potsdam, Germany.
Vert.x clustering on Docker, CoreOS and ETCDTim Nolet
This talk was held at the Vert.x Meetup Amsterdam on 30-07-2014. The subject is on how to get a Vert.X cluster running in Docker containers running on CoreOS without any manual configuration.
All you need to know about the JavaScript event loopSaša Tatar
The document discusses the JavaScript event loop and call stack. It explains that JavaScript is single-threaded with an event loop that processes tasks in the order they are received. There is a call stack that processes code synchronously, and an event queue that holds asynchronous callbacks from events like timers, promises, etc. The event loop continually checks the call stack and event queue, running tasks from the queue after the stack is empty. This allows asynchronous code to run without blocking synchronous code.
PyCon lightning talk on my Toro module for Tornadoemptysquare
With Tornado’s gen module, you can turn Python generators into full-featured coroutines, but coordination among these coroutines is difficult without mutexes, semaphores, and queues.
Toro provides to Tornado coroutines a set of locking primitives and queues analogous to those that Gevent provides to Greenlets, or that the standard library provides to threads.
The document discusses concepts related to event loops and concurrency in programming. It includes code snippets in Java showing the use of NIO selectors and channels for non-blocking I/O. Diagrams are shown illustrating reactor patterns and Vert.x modules deployed across multiple CPUs. The summary provides an overview of the main topics and techniques discussed in the technical document.
Service Discovery for Continuous Delivery with DockerTim Nolet
This talk was given at Docker Meetup Amsterdam on 10 July 2014. It describes the why, what and how we are using Docker for continuous delivery at magnetic.io and how it integrates into the platform we are building.
This document discusses Node.js architecture and how software lives in hardware. It notes that Node.js uses a single-threaded, event loop model to avoid context switching and blocking I/O. This allows high throughput for operations like HTTP requests but is not optimal for long-running computations in a single thread. The document also addresses issues like callback hell and scaling event emitters, providing solutions like using promises and external queue systems. It concludes by stating Node.js is best for I/O operations, not all problems, and event loop models have existed in other frameworks before Node.js.
This document provides an overview of the Tornado web server and summarizes its internals. It begins with an introduction to Tornado, describing it as a scalable, non-blocking web server and framework written in Python. It then outlines the main Tornado modules and discusses sockets, I/O monitoring using select, poll and epoll, and how Tornado sets up its server loop and handles requests.
Rust is a systems programming language that provides memory safety without using a garbage collector. It achieves memory safety through rules of ownership, borrowing, and lifetimes that are checked at compile time. These rules prevent common memory bugs like memory leaks, dangling pointers, and use-after-free errors that are common in C and C++.
Kotlin coroutines provide a way to write asynchronous and concurrent code using suspending functions and structured concurrency. Coroutines avoid callbacks and are lighter weight than threads. They allow suspending execution and resuming it later without blocking threads. This makes asynchronous code look synchronous and avoids issues like callback hell. Coroutines provide features like parallelism, cancellation, exception handling and context propagation to simplify concurrent programming.
This document discusses multithreaded and asynchronous programming in C# and file I/O. It covers delegates and how they allow invoking methods asynchronously on separate threads. It also discusses the Threading namespace which provides classes for creating and managing threads like Thread, ThreadStart, and Timer. The document shows examples of getting thread information, passing parameters to threads, locking for thread safety, and using the Dispatcher class to update the UI from a non-UI thread.
Bucks County Tech Meetup: node.js introductiondshkolnikov
The document provides an introduction to Node.js and JavaScript. It discusses Node.js' non-blocking I/O and event loop model. Key topics covered include the npm package manager, event emitters, asynchronous code flow using process.nextTick(), avoiding callback hell with the async module, and memory management with garbage collection in Node.js. Code examples are provided on GitHub to demonstrate various concepts hands-on.
ZeroMQ is a library for building distributed applications that provides patterns for request-reply, publish-subscribe, and pipelining between clients and services. It demonstrates using these patterns to build a hello world server and client, stock ticker publisher and subscriber, and parallel task processing pipeline. ZeroMQ supports multiple transport types and languages.
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
Charla Universidad de Valencia - http://www.uv.es/
Cátedra de Capgemini 2016/17 - http://www.uv.es/capgeminiuv/sobre_nosotros.html
Asignatura : Programación avanzada y Lenguajes de programación
Título : Paradigma FP y OOP usando técnicas avanzadas de Programación
This document provides an overview of Asynchronous I/O (ASIO) and how it can be used for network programming in C++. It discusses ASIO's implementation of the Proactor pattern and how this allows for asynchronous and non-blocking I/O. It then demonstrates how to build a simple TCP echo server using ASIO that handles multiple concurrent connections through the use of connection objects and an I/O service. It also discusses how ASIO can be used beyond just networking for other asynchronous tasks like signal handling, timers, and stream I/O.
This document discusses the Tornado web server framework. It provides an overview of Tornado, including that it is a non-blocking and scalable web server that was used by FriendFeed and is now open-sourced by Facebook. It describes Tornado's architecture, which uses an IOLoop and callbacks instead of threads to remain asynchronous and non-blocking. An example "Hello World" application in Tornado is also provided. Performance comparisons show Tornado outperforming other frameworks like Node.js and Twisted.
Tornado is a non-blocking light-weight web server and framework. There's been many introductory talks about it, and it's time to look deeper into it: not just what Tornado does, but how it does it and what can we learn from it when designing our own concurrent systems.
In this talk I go over the following topics. I cover them in two parts: first I present how to use a certain feature or approach in our applications; then, I dig into Tornado's source code to see how it really works.
- Getting Started: quickly get a simple Tornado application up and running. We'll keep digging into, changing and poking this Application for most of the talk.
- An Application Listens: what an Application is, how does Tornado start it and how does it process its requests.
- Application and IOLoop: we'll look at how the IOLoop receives the connections from the users and passes them on to the Applications.
- Scheduled Tasks: we'll see how to schedule tasks and how the IOLoop will run them.
- Generators: we'll learn to use generators to handle the responses of our asynchronous calls, and how they work with the IOLoop.
Advanced:
- Websockets: how to use them and how they work.
- IOStream: how do Tornado's non-blocking sockets work.
- Database: how to use non-blocking sockets to connect to databases.
- Process: how Tornado works with multiple processes.
I presented this talk at Europython 2012 and PyGrunn 2012.
Code examples: https://bitbucket.org/grimborg/tornado-in-depth/src/tip/examples/
Este documento presenta un resumen de las principales características de asyncio, la implementación de referencia de I/O asíncrono en Python descrita en PEP 3156. asyncio proporciona event loops, coroutines, futuros y tareas para manejar operaciones de I/O de forma asíncrona. También incluye transportes y protocolos para crear servidores y clientes TCP/IP asíncronos. El objetivo es proporcionar una implementación moderna de I/O asíncrono que funcione en todas las plataformas soportadas por Python 3.3 o
Seu primeiro loop com Python AsyncIO - TDC 2016Carlos Maniero
The document discusses asynchronous programming in Python using asyncio. It begins with motivational quotes about asynchronous programming. It then provides examples of using coroutines, tasks/futures, and event loops in asyncio. It demonstrates how asyncio avoids blocking the event loop by executing slow functions in a thread pool. The document concludes by mentioning ThreadPoolExecutor and aioHTTP as topics to explore next.
The asyncio project was officially launched with the release of Python 3.4 in March 2014. The project was public before that under the name “tulip”. asyncio is just a core network library, it requires third party library to be usable for common protocols. One year later, asyncio has a strong community writing libraries on top of it.
The most advanced library is aiohttp which includes a complete HTTP client but also a HTTP server. There are also libraries to access asynchronously the file system, resolve names with DNS, have variables local to tasks, read-write locks, etc. There are clients for AMQP, Asterisk, ElasticSearch, IRC, XMPP (Jabber), etc. (and even an IRC server!). There are asynchronous drivers for all common databases, and even for some ORMs. As expected, there are tons of new web frameworks based on asyncio. It’s also possible to plug asyncio into Gtk, Qt, gevent, eventlet, gunicorn, tornado, etc.
I will also discuss use cases of asyncio in production and benchmarks. Spoiler: asyncio is not slow.
The asyncio library also evolved to become more usable: it has a better documentation, is easier to debug and has a few new functions. There is also a port to Python 2: trollius.
This document discusses asyncio and asynchronous programming in Python. It begins by introducing the author and their experience with asyncio. It then covers topics like using yield from to write asynchronous code, how yield from works under the hood, debugging asynchronous code, task cancellation, timeouts, and more. Magic methods and third-party libraries for asyncio are also mentioned. In summary, asyncio provides a convenient API for asynchronous networking in Python using TCP/UDP sockets, Unix pipes, and processes, though the ecosystem is still growing.
El documento habla sobre la seguridad en comunicaciones SIP y RTP. Explica varios mecanismos como TLS, SRTP, ZRTP y DTLS-SRTP para cifrar las señales. Recomienda usar siempre cifrado cuando sea posible, utilizar mecanismos que ofrezcan "Forward Secrecy" y mantenerse actualizado con los últimos avances en criptografía. Además, advierte que no se debe confiar ciegamente en nadie y que es importante verificar la identidad de los participantes.
The document discusses the future of the private branch exchange (PBX) system and outlines key aspects of the SylkServer 3 product. It emphasizes simplicity through zero configuration, provisioning, and a seamless user interface. Security is ensured through secure defaults, encryption of SIP and RTP protocols, and end-to-end encryption of chat. Sharing capabilities allow for multi-party conferencing with audio, video, file transfers and screen sharing. Standards compliance and use of domains instead of phone numbers aim to future proof the system.
Slides from my talk at FOSDEM 2015 lightning talks track, about Project Open Pi Phone - http://op2-project.github.io/
Talk at PyCon Spain 2013 about async I/O in python using the new library created by Guido: asyncio (best known as tulip).
Video (spanish): https://www.youtube.com/watch?v=BlOSvIVSe_w
Code: https://github.com/igalarzab/pycones2013
El documento describe el proyecto OP^2, el cual tiene como objetivo desarrollar un dispositivo de hardware SIP abierto llamado Open Pi Phone utilizando una Raspberry Pi. El proyecto usa el SIP SIMPLE Client SDK como núcleo y provee una interfaz web y API REST para configurar el dispositivo. Se han creado dos prototipos (Falcon y FalconPlus) y el proyecto busca mejorar el audio, provisionamiento y otras funcionalidades en el futuro.
David Beazley gave a tutorial on coroutines and concurrency at PyCon 2009. The tutorial provided an overview of coroutines, how they can be used, and whether they are useful. It explored coroutines in Python using generators and the send method added in Python 2.5. The tutorial was meant to determine if coroutines have practical applications as an approach to concurrency. It focused on practical examples over academic theory and included some later performance measurements.
SylkServer is a state-of-the-art RTC application server that provides traditional SIP support as well as conferencing via SIP, XMPP, IRC, and WebRTC gateways. The latest version, SylkServer 4.0, was released for ElastixWorld 2016 and made the Sylk WebRTC client and a desktop application based on Electron open source. SylkServer offers zero configuration video conferencing and the developers are currently hiring and looking for questions.
Este documento presenta a AG Projects, una empresa especializada en infraestructura SIP para operadores. AG Projects ha desarrollado software desde 2002, incluyendo Blink, OpenSIPS y Sylk WebRTC. El documento también describe algunas de las necesidades clave de un operador como el enrutamiento de llamadas, la portabilidad y la facturación. Además, introduce SIPThor, una infraestructura SIP distribuida horizontalmente capaz de escalar a más de 9000 solicitudes por segundo de manera resiliente y tolerante a fallos.
This document provides an overview of the libuv library. Libuv is a cross-platform asynchronous I/O and event loop library written in C. It is used by Node.js and many other projects. The document discusses libuv's architecture, features like the event loop, handles, and requests. It also covers libuv's use in Node.js and the current state and future plans for libuv.
This document provides an introduction to asynchronous programming in Python using asyncio. It defines asyncio as a module that provides infrastructure for writing single-threaded concurrent code using coroutines. It discusses how asyncio allows I/O to be handled asynchronously using coroutines and without blocking threads. It highlights some benefits of asyncio like improved performance and scalability for web applications by allowing many network connections to be handled simultaneously without blocking. It provides examples of how to get started with asyncio by running coroutines concurrently using tasks and futures.
What Is Async, How Does It Work, And When Should I Use It?emptysquare
Python’s asynchronous frameworks, like asyncio, Tornado, and Twisted, are increasingly important for writing high-performance web applications. Even if you’re an experienced web programmer, you may lack a rigorous understanding of how these frameworks work and when to use them. Let’s see how asyncio's event loop works, and learn how to efficiently handle very large numbers of concurrent connections.
The document discusses concurrency solutions in Python, including built-in threading and multiprocessing modules, and third-party libraries like Twisted, Stackless Python, Kamaelia, and cogen. It provides examples of using each solution and notes that while the Global Interpreter Lock limits parallelism, these third-party frameworks provide cleaner approaches to concurrency than the built-in solutions alone.
By James Kirk Cropcho
PyData New York City 2017
Want to start learning asynchronous programming techniques, but you’re feeling blocked? In this talk, I will explain asynchronous execution. Then, using assorted asynchronous libraries and frameworks, I’ll display and discuss different implementations of a realistic application.
The journey of asyncio adoption in instagramJimmy Lai
In this talk, we share our strategy to adopt asyncio and the tools we built: including common helper library for asyncio testing/debugging/profiling, static analysis and profiling tools for identify call stack, bug fixes and optimizations for asyncio module, design patterns for asyncio, etc. Those experiences are learn from large scale project -- Instagram Django Service.
Python Ireland June Meetup @ Science Gallery.
For many programs, it's important to have some strategy for doing I/O in an async manner. This talk will attempt to provide a quick overview of the basic principles of the topic, some examples of existing support in Python frameworks and an introduction to recent work by Guido to bring async I/O support into Python core.
This document provides an overview of using asyncio for asynchronous programming in Python. It discusses what asyncio is and some key concepts like coroutines, the event loop, and the await keyword. It then demonstrates several examples of using asyncio to run asynchronous functions with coroutines, gather futures, handle synchronous code, and iterate over async iterators/generators. Common asyncio packages for web applications, databases, and networking are also mentioned.
The document discusses using asyncio to perform asynchronous web scraping in Python. It begins with an overview of common Python web scraping tools like Requests, BeautifulSoup, Scrapy. It then covers key concepts of asyncio like event loops, coroutines, tasks and futures. It provides examples of building an asynchronous web crawler and downloader using these concepts. Finally, it discusses alternatives to asyncio for asynchronous programming like ThreadPoolExecutor and ProcessPoolExecutor.
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPMykola Novik
The document discusses various approaches for dealing with blocking code within the asyncio event loop:
1. Check if a compatible asyncio library exists
2. Check if a REST API is available to avoid blocking
3. Check if there is a simple text or binary protocol that can be implemented without blocking
4. Check if there is an existing synchronous Python client that can be adapted
5. Use a thread pool executor to run blocking code in separate threads to avoid blocking the event loop
For filesystem and CPU intensive operations, the document recommends using a thread pool executor due to OS limitations on asynchronous filesystem access. The aiofiles library provides an asynchronous filesystem wrapper that uses threads in the background.
asyncio - is young library for asynchronous network programming. Lack of information on proper use and writing code in asyncio as well as production war stories slows down asyncio adoption.
In this talk I'll cover my experience with asyncio in production, best practices for writing reliable and testable asynchronous code as well as bunch of asyncio tips and tricks. We will discuss how run asyncio application in standalone mode, execute blocking code in event loop and moreover how embed asyncio in your synchronous application.
This document discusses concurrency in Python. It defines concurrency as the simultaneous occurrence of events and describes different concurrency features in Python like threading and asyncio. It explains that threading uses preemptive multitasking while asyncio uses cooperative multitasking. The document also discusses when concurrency is useful for CPU-bound versus I/O-bound programs and provides examples of using threading, asyncio, and multiprocessing to speed up I/O-bound and CPU-bound programs. In the conclusion, it recommends determining if a program is CPU-bound or I/O-bound and then choosing the appropriate concurrency approach.
The document is a presentation on Stackless Python, which extends Python with lightweight threading and tasklets. It discusses how Stackless provides more readable asynchronous code through tasklets and channels instead of callbacks. Examples show how tasklets can block and communicate without blocking the scheduler, allowing cooperative multitasking.
AsyncIO can speed up web scraping by allowing asynchronous requests and parsing to occur concurrently without blocking. It uses coroutines and an event loop to schedule tasks. For scraping, URLs can be fetched asynchronously using aiohttp. Results are gathered after tasks complete without waiting sequentially. Performance can be monitored using tools like aiomonitor which provide a task process list and console. MongoDB can be used to save crawling results with the batch ID and track success/error counts.
Gevent is a Python library that uses greenlets to provide a synchronous-looking API for asynchronous applications. It uses a single OS thread and event loop to handle many connections concurrently by switching between greenlets frequently. This allows applications to achieve high concurrency with low memory usage compared to multithreading. Gevent patches common libraries like sockets to be non-blocking and cooperative. When data is available on a socket, the socket's greenlet is resumed to process it rather than blocking the entire program.
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingJuti Noppornpitak
Since Python 3.5 and PEP 492, we have been able to write asynchronous programs in an easy and Pythonic way without external libraries. Even so, it is still difficult to understand what asynchronous programming is all about and when we, Python developers, should consider using it. This talk will give you a gentle introduction to the world of asynchronous programming, focusing mostly on the core concept of async programming, how it works, and what its applications are, in order to provide a good foundation to Python developers on the topic. On top of that, we will explore a small code example (mostly involving the built-in asyncio) and briefly exam the source code of CPython to find out how it works. This talk will also give you some brief comparison of threading.Thread and ThreadPoolExecutor.
MULTI-THREADING in python appalication.pptxSaiDhanushM
Multithreading allows a processor to execute multiple threads concurrently. It is achieved through frequent context switching between threads, where the state of one thread is saved and another is loaded on an interrupt. This gives the appearance that all threads are running in parallel through multitasking. In Python, a thread is a sequence of instructions that can run independently within a process. Multiple threads can exist within a Python process and share global variables and code, but each has its own register set and local variables. The threading module is used to create and manage threads in Python.
Dayne Jones provides an overview of asynchronous Python programming. He discusses how asynchronous programming works by using callbacks and event loops to avoid blocking and improve efficiency. Common use cases for asynchronous programming include real-time web applications with long-lived connections, network I/O like HTTP requests, database queries, and filesystem operations. The major asynchronous libraries for Python include Tornado, asyncio, Twisted, Gevent, and Cyclone. Asynchronous programming allows for high throughput by keeping threads busy handling I/O instead of blocking on single operations.
Twisted is an event-driven networking engine written in Python. It supports many protocols including web servers, chat clients/servers, mail servers, and more. Twisted uses asynchronous programming to avoid blocking and improve responsiveness for network services. The key components in Twisted are the reactor, which handles events; factories, which create protocol instances; protocols, which handle individual connections; and endpoints, which represent connections. An example asynchronous web proxy server in Twisted is presented to demonstrate its asynchronous programming model.
This document discusses key concepts for understanding asyncio in Python including I/O multiplexing, generators, coroutines, futures, and tasks. It notes that generators produce sequences instead of single values using yield, coroutines are generators that can pass data between nested generators using yield from, futures hold states and results for thread/process evaluation, and tasks wrap coroutines to execute them in event loops. Code examples for these concepts can be found at a GitHub URL provided. It also briefly mentions uvloop which is a high-performance event loop based on libuv.
This document summarizes the challenges of scaling Jitsi Meet to meet increased demand during the COVID-19 pandemic. Key issues included overloaded signaling nodes causing errors, mobile users unable to join, and new users confused by the tool. Solutions involved raising file descriptor limits, optimizing client/server messaging, enabling bridge cascading, and improving security and user interfaces. The community also helped through forums, guides and word of mouth. Looking ahead, Jitsi aims to improve efficiency and sustainability through new products while keeping meet.jit.si free.
Slides from my talk at FOSDEM 2021 on how we implemented End-to-End Encryption in Jitsi Meet.
https://fosdem.org/2021/schedule/event/e2ee/
Presentation given at CommCon 2020 on the state of Jitsi as of 2020.
Video: https://www.youtube.com/watch?reload=9&v=nHH3WLytuTk&feature=emb_title
Our story about scaling meet.jit.si amidst the COVID-19 worldwide crisis. Video here: https://youtu.be/APVp-20ATLk?t=850
Jitsi Meet is an open-source video conferencing solution that focuses on user privacy. It discusses various privacy threats like eavesdropping, user fingerprinting, and compromised devices/environments. It recommends muting video when unnecessary, hosting meetings in private spaces, and self-hosting the Jitsi software which is open-source and can be built without Google libraries. Features like background blurring and voice obfuscation are in development to further protect user privacy during video calls.
Este documento resume los objetivos y logros del proyecto de código abierto Jitsi. Jitsi busca facilitar comunicaciones privadas y basadas en estándares abiertos a través del desarrollo de proyectos y SDKs fáciles de usar e integrar. Jitsi es un conjunto de proyectos para la creación de sistemas de videoconferencia escalables y seguros. El documento luego detalla mejoras recientes en el chat, audio, compartir pantalla y video, así como nuevas integraciones y modos para dispositivos móviles.
Talk given at OpenSIPs summit 2019. Video: https://www.youtube.com/watch?v=VwfCkLEZ5U4&list=PLMMZA6ketvKpnVs9a1ViR06JkZPEYzE8N&index=11&t=0s
Slides from the talk given at FOSDEM 2019 on how Jitsi Meet was brought from the web to mobile and how we built a native SDK using React Native.
Video: https://fosdem.org/2019/schedule/event/jitsi_mobile_webrtc/
Jitsi es una solución de videoconferencia de código abierto que permite llamadas seguras y escalables. El documento describe las actualizaciones recientes de Jitsi, incluyendo mejoras en las aplicaciones móviles y de escritorio, integraciones con calendarios y Slack, optimizaciones en el uso de ancho de banda, y planes futuros para cifrado de extremo a extremo y una comunidad en crecimiento. Jitsi ofrece características completas con poco esfuerzo de integración y una licencia de código abierto.
Jitsi: state-of-the-art video conferencing you can self-hostSaúl Ibarra Corretgé
Jitsi is an open source project that allows users to easily deploy secure and scalable video conferencing solutions. It provides high quality audio and video calling through mobile apps, web interfaces and APIs. The project uses adaptive technology to optimize video quality based on available bandwidth. It has a large community of contributors helping to improve the software and is licensed under Apache 2.
Slides from my talk at OpenSIPS Summit 2017 and KamailioWorld 2017, showing the capabilities of Jitsi Meet, and a novel way for doing SIP video room integration.
Video at KamailioWorld: https://www.youtube.com/watch?v=TGloLKOrvmo
Dangerous Demo at KamailioWorld: https://www.youtube.com/watch?v=d0zHiLkHDyY&feature=youtu.be&t=3589
Slides from my talk at the Real Time Communications Devroom at FOSDEM 2017. Video: http://video.fosdem.org/2017/K.3.401/jitsi.mp4
WebRTC is an API that enables real-time communication directly in web browsers without plugins. The document discusses using WebRTC to build a "call roulette" application in Python with asyncio and aiohttp that randomly connects two users in real-time video/audio calls. It describes the WebRTC APIs getUserMedia, RTCPeerConnection, and RTCDataChannel and outlines a signaling protocol to connect users. The application architecture uses asyncio for asynchronous I/O and aiohttp for HTTP/WebSocket support.
Jira Administration Training – Day 1 : IntroductionRavi Teja
This presentation covers the basics of Jira for beginners. Learn how Jira works, its key features, project types, issue types, and user roles. Perfect for anyone new to Jira or preparing for Jira Admin roles.
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPathCommunity
Join the UiPath Community Berlin (Virtual) meetup on May 27 to discover handy Studio Tips & Tricks and get introduced to UiPath Insights. Learn how to boost your development workflow, improve efficiency, and gain visibility into your automation performance.
📕 Agenda:
- Welcome & Introductions
- UiPath Studio Tips & Tricks for Efficient Development
- Best Practices for Workflow Design
- Introduction to UiPath Insights
- Creating Dashboards & Tracking KPIs (Demo)
- Q&A and Open Discussion
Perfect for developers, analysts, and automation enthusiasts!
This session streamed live on May 27, 18:00 CET.
Check out all our upcoming UiPath Community sessions at:
👉 https://community.uipath.com/events/
Join our UiPath Community Berlin chapter:
👉 https://community.uipath.com/berlin/
AI Emotional Actors: “When Machines Learn to Feel and Perform"AkashKumar809858
Welcome to the era of AI Emotional Actors.
The entertainment landscape is undergoing a seismic transformation. What started as motion capture and CGI enhancements has evolved into a full-blown revolution: synthetic beings not only perform but express, emote, and adapt in real time.
For reading further follow this link -
https://akash97.gumroad.com/l/meioex
Contributing to WordPress With & Without Code.pptxPatrick Lumumba
Contributing to WordPress: Making an Impact on the Test Team—With or Without Coding Skills
WordPress survives on collaboration, and the Test Team plays a very important role in ensuring the CMS is stable, user-friendly, and accessible to everyone.
This talk aims to deconstruct the myth that one has to be a developer to contribute to WordPress. In this session, I will share with the audience how to get involved with the WordPress Team, whether a coder or not.
We’ll explore practical ways to contribute, from testing new features, and patches, to reporting bugs. By the end of this talk, the audience will have the tools and confidence to make a meaningful impact on WordPress—no matter the skill set.
Supercharge Your AI Development with Local LLMsFrancesco Corti
In today's AI development landscape, developers face significant challenges when building applications that leverage powerful large language models (LLMs) through SaaS platforms like ChatGPT, Gemini, and others. While these services offer impressive capabilities, they come with substantial costs that can quickly escalate especially during the development lifecycle. Additionally, the inherent latency of web-based APIs creates frustrating bottlenecks during the critical testing and iteration phases of development, slowing down innovation and frustrating developers.
This talk will introduce the transformative approach of integrating local LLMs directly into their development environments. By bringing these models closer to where the code lives, developers can dramatically accelerate development lifecycles while maintaining complete control over model selection and configuration. This methodology effectively reduces costs to zero by eliminating dependency on pay-per-use SaaS services, while opening new possibilities for comprehensive integration testing, rapid prototyping, and specialized use cases.
Neural representations have shown the potential to accelerate ray casting in a conventional ray-tracing-based rendering pipeline. We introduce a novel approach called Locally-Subdivided Neural Intersection Function (LSNIF) that replaces bottom-level BVHs used as traditional geometric representations with a neural network. Our method introduces a sparse hash grid encoding scheme incorporating geometry voxelization, a scene-agnostic training data collection, and a tailored loss function. It enables the network to output not only visibility but also hit-point information and material indices. LSNIF can be trained offline for a single object, allowing us to use LSNIF as a replacement for its corresponding BVH. With these designs, the network can handle hit-point queries from any arbitrary viewpoint, supporting all types of rays in the rendering pipeline. We demonstrate that LSNIF can render a variety of scenes, including real-world scenes designed for other path tracers, while achieving a memory footprint reduction of up to 106.2x compared to a compressed BVH.
https://arxiv.org/abs/2504.21627
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Lorenzo Miniero
Slides for my "Multistream support in the Janus SIP and NoSIP plugins" presentation at the OpenSIPS Summit 2025 event.
They describe my efforts refactoring the Janus SIP and NoSIP plugins to allow for the gatewaying of an arbitrary number of audio/video streams per call (thus breaking the current 1-audio/1-video limitation), plus some additional considerations on what this could mean when dealing with application protocols negotiated via SIP as well.
6th Power Grid Model Meetup
Join the Power Grid Model community for an exciting day of sharing experiences, learning from each other, planning, and collaborating.
This hybrid in-person/online event will include a full day agenda, with the opportunity to socialize afterwards for in-person attendees.
If you have a hackathon proposal, tell us when you register!
About Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
Dev Dives: System-to-system integration with UiPath API WorkflowsUiPathCommunity
Join the next Dev Dives webinar on May 29 for a first contact with UiPath API Workflows, a powerful tool purpose-fit for API integration and data manipulation!
This session will guide you through the technical aspects of automating communication between applications, systems and data sources using API workflows.
📕 We'll delve into:
- How this feature delivers API integration as a first-party concept of the UiPath Platform.
- How to design, implement, and debug API workflows to integrate with your existing systems seamlessly and securely.
- How to optimize your API integrations with runtime built for speed and scalability.
This session is ideal for developers looking to solve API integration use cases with the power of the UiPath Platform.
👨🏫 Speakers:
Gunter De Souter, Sr. Director, Product Manager @UiPath
Ramsay Grove, Product Manager @UiPath
This session streamed live on May 29, 2025, 16:00 CET.
Check out all our upcoming UiPath Dev Dives sessions:
👉 https://community.uipath.com/dev-dives-automation-developer-2025/
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...James Anderson
The Quantum Apocalypse: A Looming Threat & The Need for Post-Quantum Encryption
We explore the imminent risks posed by quantum computing to modern encryption standards and the urgent need for post-quantum cryptography (PQC).
Bio: With 30 years in cybersecurity, including as a CISO, Tommy is a strategic leader driving security transformation, risk management, and program maturity. He has led high-performing teams, shaped industry policies, and advised organizations on complex cyber, compliance, and data protection challenges.
Co-Constructing Explanations for AI Systems using ProvenancePaul Groth
Explanation is not a one off - it's a process where people and systems work together to gain understanding. This idea of co-constructing explanations or explanation by exploration is powerful way to frame the problem of explanation. In this talk, I discuss our first experiments with this approach for explaining complex AI systems by using provenance. Importantly, I discuss the difficulty of evaluation and discuss some of our first approaches to evaluating these systems at scale. Finally, I touch on the importance of explanation to the comprehensive evaluation of AI systems.
Cyber Security Legal Framework in Nepal.pptxGhimire B.R.
The presentation is about the review of existing legal framework on Cyber Security in Nepal. The strength and weakness highlights of the major acts and policies so far. Further it highlights the needs of data protection act .
Introducing FME Realize: A New Era of Spatial Computing and ARSafe Software
A new era for the FME Platform has arrived – and it’s taking data into the real world.
Meet FME Realize: marking a new chapter in how organizations connect digital information with the physical environment around them. With the addition of FME Realize, FME has evolved into an All-data, Any-AI Spatial Computing Platform.
FME Realize brings spatial computing, augmented reality (AR), and the full power of FME to mobile teams: making it easy to visualize, interact with, and update data right in the field. From infrastructure management to asset inspections, you can put any data into real-world context, instantly.
Join us to discover how spatial computing, powered by FME, enables digital twins, AI-driven insights, and real-time field interactions: all through an intuitive no-code experience.
In this one-hour webinar, you’ll:
-Explore what FME Realize includes and how it fits into the FME Platform
-Learn how to deliver real-time AR experiences, fast
-See how FME enables live, contextual interactions with enterprise data across systems
-See demos, including ones you can try yourself
-Get tutorials and downloadable resources to help you start right away
Whether you’re exploring spatial computing for the first time or looking to scale AR across your organization, this session will give you the tools and insights to get started with confidence.
Maxx nft market place new generation nft marketing placeusersalmanrazdelhi
PREFACE OF MAXXNFT
MaxxNFT: Powering the Future of Digital Ownership
MaxxNFT is a cutting-edge Web3 platform designed to revolutionize how
digital assets are owned, traded, and valued. Positioned at the forefront of the
NFT movement, MaxxNFT views NFTs not just as collectibles, but as the next
generation of internet equity—unique, verifiable digital assets that unlock new
possibilities for creators, investors, and everyday users alike.
Through strategic integrations with OKT Chain and OKX Web3, MaxxNFT
enables seamless cross-chain NFT trading, improved liquidity, and enhanced
user accessibility. These collaborations make it easier than ever to participate
in the NFT ecosystem while expanding the platform’s global reach.
With a focus on innovation, user rewards, and inclusive financial growth,
MaxxNFT offers multiple income streams—from referral bonuses to liquidity
incentives—creating a vibrant community-driven economy. Whether you
'
re
minting your first NFT or building a digital asset portfolio, MaxxNFT empowers
you to participate in the future of decentralized value exchange.
https://maxxnft.xyz/
Offshore IT Support: Balancing In-House and Offshore Help Desk Techniciansjohn823664
In today's always-on digital environment, businesses must deliver seamless IT support across time zones, devices, and departments. This SlideShare explores how companies can strategically combine in-house expertise with offshore talent to build a high-performing, cost-efficient help desk operation.
From the benefits and challenges of offshore support to practical models for integrating global teams, this presentation offers insights, real-world examples, and key metrics for success. Whether you're scaling a startup or optimizing enterprise support, discover how to balance cost, quality, and responsiveness with a hybrid IT support strategy.
Perfect for IT managers, operations leads, and business owners considering global help desk solutions.
Microsoft Build 2025 takeaways in one presentationDigitalmara
Microsoft Build 2025 introduced significant updates. Everything revolves around AI. DigitalMara analyzed these announcements:
• AI enhancements for Windows 11
By embedding AI capabilities directly into the OS, Microsoft is lowering the barrier for users to benefit from intelligent automation without requiring third-party tools. It's a practical step toward improving user experience, such as streamlining workflows and enhancing productivity. However, attention should be paid to data privacy, user control, and transparency of AI behavior. The implementation policy should be clear and ethical.
• GitHub Copilot coding agent
The introduction of coding agents is a meaningful step in everyday AI assistance. However, it still brings challenges. Some people compare agents with junior developers. They noted that while the agent can handle certain tasks, it often requires supervision and can introduce new issues. This innovation holds both potential and limitations. Balancing automation with human oversight is crucial to ensure quality and reliability.
• Introduction of Natural Language Web
NLWeb is a significant step toward a more natural and intuitive web experience. It can help users access content more easily and reduce reliance on traditional navigation. The open-source foundation provides developers with the flexibility to implement AI-driven interactions without rebuilding their existing platforms. NLWeb is a promising level of web interaction that complements, rather than replaces, well-designed UI.
• Introduction of Model Context Protocol
MCP provides a standardized method for connecting AI models with diverse tools and data sources. This approach simplifies the development of AI-driven applications, enhancing efficiency and scalability. Its open-source nature encourages broader adoption and collaboration within the developer community. Nevertheless, MCP can face challenges in compatibility across vendors and security in context sharing. Clear guidelines are crucial.
• Windows Subsystem for Linux is open-sourced
It's a positive step toward greater transparency and collaboration in the developer ecosystem. The community can now contribute to its evolution, helping identify issues and expand functionality faster. However, open-source software in a core system also introduces concerns around security, code quality management, and long-term maintenance. Microsoft’s continued involvement will be key to ensuring WSL remains stable and secure.
• Azure AI Foundry platform hosts Grok 3 AI models
Adding new models is a valuable expansion of AI development resources available at Azure. This provides developers with more flexibility in choosing language models that suit a range of application sizes and needs. Hosting on Azure makes access and integration easier when using Microsoft infrastructure.
7. The Async Way (TM)
Single thread
Block waiting for sockets to be ready to read or
write
Perform i/o operations and call the callbacks!
Repeat
(Windows is not like this)
8. Why asyncio?
asyncore and asynchat are not enough
Fresh new implementation of Asynchronous I/O
Python >= 3.3
Trollius: backport for Python >= 2.6
Use new language features: yield from
Designed to interoperate with other frameworks
12. Coroutines, futures & tasks
Coroutine
generator function, can receive values
decorated with @coroutine
Future
promise of a result or an error
Task
Future which runs a coroutine
13. Futures
Similar to Futures from PEP-3148
concurrent.futures.Future
API (almost) identical:
f.set_result(); r = f.result()
f.set_exception(e); e = f.exception()
f.done(); f.cancel(); f.cancelled()
f.add_done_callback(x); f.remove_done_callback(x)
14. Futures + Coroutines
yield from works with Futures!
f = Future()
Someone will set the result or exception
r = yield from f
Waits until done and returns f.result()
Usually returned by functions
16. Tasks
Unicorns covered in fairy dust
It’s a coroutine wrapped in a Future
WAT
Inherits from Future
Works with yield from!
r = yield from Task(coro(...))
17. Tasks vs coroutines
A coroutine doesn’t “advance” without a
scheduling mechanism
Tasks can advance on their own
The event loop is the scheduler!
Magic!
18. Echo Server
import asyncio
loop = asyncio.get_event_loop()
class EchoProtocol(asyncio.Protocol):
def connection_made(self, transport):
print('Client connected')
self.transport = transport
def data_received(self, data):
print('Received data:',data)
self.transport.write(data)
def connection_lost(self, exc):
print('Connection closed', exc)
f = loop.create_server(lambda: EchoProtocol(), 'localhost', 1234)
server = loop.run_until_complete(f)
print('Server started')
loop.run_forever()
19. Echo Server Reloaded
import asyncio
loop = asyncio.get_event_loop()
clients = {} # task -> (reader, writer)
def accept_client(client_reader, client_writer):
task = asyncio.Task(handle_client(client_reader, client_writer))
clients[task] = (client_reader, client_writer)
def client_done(task):
del clients[task]
task.add_done_callback(client_done)
@asyncio.coroutine
def handle_client(client_reader, client_writer):
while True:
data = (yield from client_reader.readline())
client_writer.write(data)
f = asyncio.start_server(accept_client, '127.0.0.1', 1234)
server = loop.run_until_complete(f)
loop.run_forever()
21. Redis
import asyncio
import asyncio_redis
@asyncio.coroutine
def subscriber(channels):
# Create connection
connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379)
# Create subscriber.
subscriber = yield from connection.start_subscribe()
# Subscribe to channel.
yield from subscriber.subscribe(channels)
# Wait for incoming events.
while True:
reply = yield from subscriber.next_published()
print('Received: ', repr(reply.value), 'on channel', reply.channel)
loop = asyncio.get_event_loop()
loop.run_until_complete(subscriber(['my-channel']))
22. More?
We just scratched the surface!
Read PEP-3156 (it’s an easy read, I promise!)
Checkout the documentation
Checkout the third-party libraries
Go implement something cool!
“I hear and I forget. I see and I remember.
I do and I understand.” - Confucius