<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: keshavadk</title>
    <description>The latest articles on DEV Community by keshavadk (@keshavadk).</description>
    <link>https://dev.to/keshavadk</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F316168%2F3abbfafd-533a-43df-9a91-78015485bffb.jpeg</url>
      <title>DEV Community: keshavadk</title>
      <link>https://dev.to/keshavadk</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/keshavadk"/>
    <language>en</language>
    <item>
      <title>Mastering Python Context Managers: Efficient Resource Management Made Easy</title>
      <dc:creator>keshavadk</dc:creator>
      <pubDate>Mon, 10 Feb 2025 19:46:07 +0000</pubDate>
      <link>https://dev.to/keshavadk/mastering-python-context-managers-efficient-resource-management-made-easy-2npb</link>
      <guid>https://dev.to/keshavadk/mastering-python-context-managers-efficient-resource-management-made-easy-2npb</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
In Python, managing resources like file handling, database connections, and network sockets efficiently is crucial to prevent memory leaks and ensure clean execution. Context Managers simplify this process by automatically handling resource allocation and deallocation. In this article, we will explore how context managers work, their use cases, and how to implement them in Python.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a Context Manager?&lt;/strong&gt;&lt;br&gt;
A context manager is a special construct in Python that allows you to manage resources using the with statement. It ensures that resources are properly initialized and cleaned up after use, even if an exception occurs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Context Managers Work?&lt;/strong&gt;&lt;br&gt;
A context manager in Python has two essential methods:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;enter&lt;/strong&gt;(): This method is executed when entering the with block. It allocates resources and returns the resource handle.&lt;br&gt;
&lt;strong&gt;exit&lt;/strong&gt;(): This method is executed when the with block ends. It ensures proper cleanup of the resource, such as closing files or releasing locks.&lt;/p&gt;

&lt;p&gt;Example: File Handling with Context Manager&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Opening a file using context manager
with open("sample.txt", "w") as file:
    file.write("Hello, Python!")

# File is automatically closed after the with block ends

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Benefit: No need to manually call file.close(), even if an error occurs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Context Managers?&lt;/strong&gt;&lt;br&gt;
Using context managers provides several advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Automatic Resource Management – No need to explicitly release resources like closing files or database connections.&lt;/li&gt;
&lt;li&gt;Exception Safety – Ensures proper cleanup even if an error occurs.&lt;/li&gt;
&lt;li&gt;Cleaner &amp;amp; Readable Code – Eliminates the need for try-finally blocks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Cases of Context Managers&lt;/strong&gt;&lt;br&gt;
Point 1. Managing Database Connections&lt;br&gt;
Handling databases requires proper connection management. Using a context manager ensures that the database connection is committed and closed properly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import sqlite3

class DatabaseManager:
    def __init__(self, db_name):
        self.db_name = db_name

    def __enter__(self):
        self.conn = sqlite3.connect(self.db_name)
        return self.conn.cursor()

    def __exit__(self, exc_type, exc_value, traceback):
        self.conn.commit()
        self.conn.close()

# Using the context manager
with DatabaseManager("test.db") as cursor:
    cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
    cursor.execute("INSERT INTO users (name) VALUES ('Alice')")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ensures that the database connection is committed and closed after execution.&lt;/p&gt;

&lt;p&gt;Point 2. Thread Synchronization with Locks&lt;br&gt;
When working with multithreading, locks prevent race conditions. Context managers help acquire and release locks automatically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import threading

lock = threading.Lock()

def critical_section():
    with lock:  # Acquires lock before execution and releases it after
        print("Thread-safe operation in progress")

# Using threads
thread1 = threading.Thread(target=critical_section)
thread2 = threading.Thread(target=critical_section)

thread1.start()
thread2.start()
thread1.join()
thread2.join()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Prevents multiple threads from accessing shared resources simultaneously.&lt;/p&gt;

&lt;p&gt;Point 3. Handling Temporary Files&lt;br&gt;
Python’s tempfile module creates temporary files that are automatically cleaned up when out of scope.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import tempfile

with tempfile.TemporaryFile(mode="w+") as temp:
    temp.write("Temporary data")
    temp.seek(0)
    print(temp.read())  # Read from temp file
# File is automatically deleted after the with block

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Useful when handling temporary storage needs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating a Custom Context Manager&lt;/strong&gt;&lt;br&gt;
You can create a custom context manager using a class-based approach or a function-based approach with contextlib.&lt;/p&gt;

&lt;p&gt;Point 1. Using a Class (with &lt;strong&gt;enter&lt;/strong&gt; and &lt;strong&gt;exit&lt;/strong&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()

# Using the custom context manager
with FileManager("test.txt", "w") as f:
    f.write("Hello from custom context manager!")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Manages file opening and closing automatically.&lt;/p&gt;

&lt;p&gt;Point 2. Using contextlib (Simpler Approach)&lt;br&gt;
Python’s contextlib module provides a decorator @contextmanager to simplify context manager creation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from contextlib import contextmanager

@contextmanager
def open_file(filename, mode):
    file = open(filename, mode)
    try:
        yield file  # Provide file handle
    finally:
        file.close()  # Cleanup

with open_file("test.txt", "w") as f:
    f.write("Using @contextmanager in Python")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Less boilerplate code compared to class-based approach.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Context Managers in Python streamline resource management, making code cleaner and more efficient. Whether handling files, databases, threads, or temporary files, they ensure that resources are correctly allocated and released.&lt;/p&gt;

&lt;p&gt;If you're working on real-world applications, leveraging context managers will improve code reliability and reduce errors. Start using them today for better Python programming! &lt;/p&gt;

</description>
      <category>python</category>
      <category>datascience</category>
      <category>softwaredevelopment</category>
      <category>pythontips</category>
    </item>
    <item>
      <title>A Beginner’s Guide to Kafka with Python: Real-Time Data Processing and Applications</title>
      <dc:creator>keshavadk</dc:creator>
      <pubDate>Fri, 01 Nov 2024 08:29:36 +0000</pubDate>
      <link>https://dev.to/keshavadk/a-beginners-guide-to-kafka-with-python-real-time-data-processing-and-applications-35o6</link>
      <guid>https://dev.to/keshavadk/a-beginners-guide-to-kafka-with-python-real-time-data-processing-and-applications-35o6</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Finzo7njlbomuyqs7hl2g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Finzo7njlbomuyqs7hl2g.png" alt="Image description" width="607" height="221"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction to Kafka&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Kafka is an open-source distributed event streaming platform developed by Apache.&lt;/li&gt;
&lt;li&gt;Originally created by LinkedIn, it was designed to handle high throughput, fault-tolerant, and real-time data streaming.&lt;/li&gt;
&lt;li&gt;Kafka allows systems to publish and subscribe to streams of records (messages), process them, and store them efficiently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Why is Kafka Used?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;High Throughput: Kafka can handle millions of messages per second.&lt;/li&gt;
&lt;li&gt;Fault Tolerance: Kafka is distributed, meaning it can replicate data across multiple nodes to ensure reliability.&lt;/li&gt;
&lt;li&gt;Durability: Kafka persists data to disk and can replay messages, ensuring reliability in message delivery.&lt;/li&gt;
&lt;li&gt;Real-time Processing: Kafka can process streams of data in real-time, ideal for applications like monitoring, analytics, or event-driven systems.&lt;/li&gt;
&lt;li&gt;Scalability: Kafka can easily scale by adding more brokers to handle large volumes of data.&lt;/li&gt;
&lt;li&gt;Decoupling Systems: Kafka acts as a middle layer for messaging, allowing different systems to communicate asynchronously.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kafka Architecture&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8z85qv5gn013xnoc1p3p.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8z85qv5gn013xnoc1p3p.jpg" alt="Image description" width="746" height="371"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Components:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Producers:&lt;/strong&gt;&lt;br&gt;
These are the applications or services that send data/messages to Kafka. Producers push messages to specific Topics within Kafka.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Topics:&lt;/strong&gt; &lt;br&gt;
A Topic is a category or feed name to which records are published. Topics are partitioned to allow for scalability and parallelism.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Partitions:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Each Topic is divided into one or more Partitions.&lt;/li&gt;
&lt;li&gt;Partitions enable Kafka to handle more messages and support 
    parallel processing.&lt;/li&gt;
&lt;li&gt;Each Partition has a unique ID and can store a subset of the 
    topic’s data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Brokers:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Kafka runs as a cluster of Brokers (servers), each handling data 
  for multiple topics and partitions.&lt;/li&gt;
&lt;li&gt;Brokers store and manage partitions, handling read and write 
  requests from Producers and Consumers.&lt;/li&gt;
&lt;li&gt;Each Broker is identified by a unique ID.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Consumers:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consumers are applications or services that read messages from topics.&lt;br&gt;
Consumers subscribe to topics, pulling data from Kafka brokers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Consumer Groups:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Consumers are organized into Consumer Groups.&lt;/li&gt;
&lt;li&gt;Each message within a partition is delivered to only one consumer within the group, which enables load balancing across multiple consumers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;ZooKeeper:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ZooKeeper manages and coordinates Kafka brokers, keeping track of brokers, topics, and partitions.&lt;/li&gt;
&lt;li&gt;It helps manage the leader election for partitions and monitors cluster health.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Cases of Kafka&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Real-time Analytics: Companies use Kafka to process and analyze streams of data in real-time for monitoring systems, like financial transaction analysis.&lt;/li&gt;
&lt;li&gt;Log Aggregation: Kafka consolidates logs from multiple services or applications for processing, alerting, or storing.&lt;/li&gt;
&lt;li&gt;Data Pipelines: Kafka is used as a backbone for transferring large amounts of data between different systems or services (ETL pipelines).&lt;/li&gt;
&lt;li&gt;IoT Applications: Kafka can handle the data streams from IoT sensors, allowing real-time analysis and responses.&lt;/li&gt;
&lt;li&gt;Microservices Communication: Kafka serves as a reliable messaging platform for microservices architectures, enabling asynchronous, decoupled communication.&lt;/li&gt;
&lt;li&gt;Real-Time Vehicle Tracking: The following example illustrates how Kafka is used to track vehicles in real-time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example using Python to demonstrate how Kafka can be used in a real-time scenario :&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Location tracking for a ride-sharing app.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For simplicity, we’ll use the kafka-python library to create both a producer (to simulate a driver sending location updates) and a consumer (to simulate a service that processes these location updates).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Setup Kafka&lt;/strong&gt;&lt;br&gt;
Make sure you have Kafka running locally or use a cloud provider. You can download and run Kafka locally by following the Kafka Quickstart Guide.&lt;br&gt;
&lt;a href="https://kafka.apache.org/quickstart" rel="noopener noreferrer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Install Kafka Python Library&lt;/strong&gt;&lt;br&gt;
You can install the Kafka Python library using pip:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install kafka-python
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Python Kafka Producer (Simulating Driver Location Updates)&lt;/strong&gt;&lt;br&gt;
The producer simulates a driver sending location updates to a Kafka topic (driver-location).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from kafka import KafkaProducer
import json
import time
import random

# Kafka Producer
producer = KafkaProducer(
    bootstrap_servers=['localhost:9092'],
    value_serializer=lambda v: json.dumps(v).encode('utf-8')  # Serialize data to JSON
)

def send_location_updates(driver_id):
    while True:
        # Simulating random GPS coordinates (latitude, longitude)
        location = {
            "driver_id": driver_id,
            "latitude": round(random.uniform(40.0, 41.0), 6),
            "longitude": round(random.uniform(-74.0, -73.0), 6),
            "timestamp": time.time()
        }
        # Send location data to Kafka
        producer.send('driver-location', location)
        print(f"Sent: {location}")
        time.sleep(5)  # Sleep for 5 seconds to simulate real-time updates

# Start sending updates for driver_id = 101
send_location_updates(driver_id=101)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Python Kafka Consumer (Simulating Ride Matching Service)&lt;/strong&gt;&lt;br&gt;
The consumer reads the location updates from the driver-location topic and processes them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from kafka import KafkaConsumer
import json

# Kafka Consumer
consumer = KafkaConsumer(
    'driver-location',
    bootstrap_servers=['localhost:9092'],
    auto_offset_reset='earliest',  # Start from the earliest message
    enable_auto_commit=True,
    group_id='location-group',
    value_deserializer=lambda x: json.loads(x.decode('utf-8'))  # Deserialize data from JSON
)

def process_location_updates():
    print("Waiting for location updates...")
    for message in consumer:
        location = message.value
        driver_id = location['driver_id']
        latitude = location['latitude']
        longitude = location['longitude']
        timestamp = location['timestamp']
        print(f"Received location update for Driver {driver_id}: ({latitude}, {longitude}) at {timestamp}")

# Start consuming location updates
process_location_updates()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Producer (Driver sending location updates):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The producer sends a JSON object to the Kafka topic driver-location with fields like driver_id, latitude, longitude, and timestamp.&lt;/li&gt;
&lt;li&gt;The producer simulates real-time GPS updates by sending location data every 5 seconds.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Consumer (Ride-matching service):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The consumer subscribes to the driver-location topic, listening for updates.&lt;/li&gt;
&lt;li&gt;Each time a location update is published to Kafka, the consumer processes and prints it, simulating a service that uses this data to match drivers and riders.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Running the Example (I am running on windows machine):&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Start the Zookeeper&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Start your local Kafka server.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.\bin\windows\kafka-server-start.bat .\config\server.properties
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now Run the producer and Consumer in 2 seperate terminal windows using python.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Run the producer script to simulate the driver sending location updates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Run the consumer script to see the ride-matching service processing the location updates in real-time.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Apache Kafka provides an exceptional platform for managing real-time data streams. By combining Kafka with Python, developers can build powerful data pipelines and real-time analytics solutions.&lt;/p&gt;

&lt;p&gt;Whether it’s vehicle tracking, IoT data, or real-time dashboards, Kafka with Python is highly scalable and can be adapted to various use cases. So, start experimenting with Kafka, and you’ll be amazed by its potential in real-world applications!&lt;/p&gt;

</description>
      <category>python</category>
      <category>datascience</category>
      <category>kafka</category>
      <category>dataanalytics</category>
    </item>
    <item>
      <title>Understanding WebSockets using Python</title>
      <dc:creator>keshavadk</dc:creator>
      <pubDate>Sun, 08 Sep 2024 12:04:06 +0000</pubDate>
      <link>https://dev.to/keshavadk/understanding-websockets-using-python-4i1c</link>
      <guid>https://dev.to/keshavadk/understanding-websockets-using-python-4i1c</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In today’s digital landscape, where real-time communication is important. traditional HTTP falls short due to its request-response model and inherent latency. As businesses and applications increasingly demand instantaneous data transfer — whether it’s live stock updates, multiplayer gaming, or collaborative tools — WebSockets have emerged as a game-changing technology. Unlike HTTP, WebSockets enable full-duplex, bi-directional communication, allowing both the server and client to send and receive messages in real-time over a single, persistent connection. This not only reduces overhead but also significantly improves the performance and responsiveness of web applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is WebSocket&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;WebSocket is a communication protocol that provides full-duplex communication channels over a single, long-lived TCP connection. This means that once a WebSocket connection is established between a client and a server, both parties can send and receive data simultaneously and continuously without the need to reopen a connection. WebSocket was designed to be efficient and low-latency, making it ideal for real-time applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why WebSocket ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;WebSockets are used in scenarios where real-time communication between a client and a server is needed. Unlike traditional HTTP, which follows a request-response model where the client must initiate every request, WebSockets allow for bi-directional communication. This makes WebSockets particularly useful in applications where data needs to be pushed from the server to the client in real time without the client having to request it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real world Use Cases&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Chat Applications: WebSockets are commonly used in chat applications where messages need to be sent and received in real time without delay.&lt;/li&gt;
&lt;li&gt;Live Streaming: WebSockets can be used to stream live video or audio, allowing the server to push new content to the client as it becomes available.&lt;/li&gt;
&lt;li&gt;Collaborative Platforms: In collaborative tools like Google Docs, WebSockets allow multiple users to see real-time changes made by others without needing to refresh the page.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;WebSockets vs HTTP&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Communication Model&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP: Follows a request-response model where the client initiates a request, and the server responds. After the response, the connection is closed.&lt;/li&gt;
&lt;li&gt;WebSockets: WebSockets provide a full-duplex, long-lived connection where both the client and server can send and receive data continuously without reopening the connection each time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Connection Handling&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP: Each request opens a new connection, and the connection is closed after the response.&lt;/li&gt;
&lt;li&gt;WebSockets: After the initial handshake (using HTTP), the connection is kept open, allowing real-time communication without the need for re-establishing connections.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Efficiency&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP: Suitable for one-time communication or transactions where requests are infrequent. It is stateless, so for continuous communication, techniques like long-polling are used, which can be resource-intensive.&lt;/li&gt;
&lt;li&gt;WebSockets: WebSockets are efficient for real-time and bi-directional communication since the connection is kept open. They use fewer resources compared to techniques like long-polling.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Latency&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP: There is always a delay (latency) as the client must request, and the server must respond. This is inefficient for real-time use cases.&lt;/li&gt;
&lt;li&gt;WebSockets: After the connection is established, data can flow almost instantly between client and server, reducing latency and making it ideal for real-time applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use Case&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP: Best suited for traditional web applications where requests are initiated by the client (e.g., REST APIs).&lt;/li&gt;
&lt;li&gt;WebSockets: Ideal for real-time applications like chat apps, stock trading platforms, live dashboards, and online gaming.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages of WebSockets&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Real-Time Communication: WebSockets allow for real-time, low-latency communication, making them ideal for applications that need instant updates.&lt;/li&gt;
&lt;li&gt;Bi-Directional Data Flow: Both client and server can send and receive data at any time, unlike HTTP where the server can only respond to client-initiated requests.&lt;/li&gt;
&lt;li&gt;Reduced Overhead: By keeping the connection open, WebSockets reduce the need to repeatedly establish new HTTP connections, saving bandwidth and reducing latency.&lt;/li&gt;
&lt;li&gt;Efficiency: WebSockets use fewer resources compared to long-polling or HTTP requests for continuous data transfer.&lt;/li&gt;
&lt;li&gt;Scalability: WebSockets can handle many concurrent connections efficiently, making them suitable for scalable real-time applications.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;How WebSockets Work&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Handshake: A WebSocket connection starts with an HTTP handshake. The client sends a request to the server with an Upgrade header to switch the connection protocol from HTTP to WebSocket.&lt;/li&gt;
&lt;li&gt;Connection Established: After the handshake, the connection is established. The server and client maintain a persistent, open TCP connection.&lt;/li&gt;
&lt;li&gt;Full-Duplex Communication: Once the WebSocket connection is open, data can be sent back and forth simultaneously. Both the server and the client can initiate communication at any time.&lt;/li&gt;
&lt;li&gt;Close Connection: Either the server or the client can close the connection when it’s no longer needed. This terminates the session and releases the resources.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Use Cases for WebSockets&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Chat Applications: Instant messaging services like WhatsApp and Slack use WebSockets for real-time messaging between users.&lt;/li&gt;
&lt;li&gt;Live Updates: WebSockets power real-time data updates in applications such as financial trading platforms (stock prices), sports scores, or live news feeds.&lt;/li&gt;
&lt;li&gt;Collaborative Tools: WebSockets enable real-time updates in collaborative tools like Google Docs or Figma, where multiple users can edit a document simultaneously.&lt;/li&gt;
&lt;li&gt;Online Gaming: Multiplayer games rely on WebSockets for real-time player actions and interactions.&lt;/li&gt;
&lt;li&gt;IoT and Sensor Data: Devices with real-time data streaming (e.g., IoT devices, weather sensors) use WebSockets to send continuous updates.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Building Real-Time Applications with Python and WebSockets&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s build a real-time application using WebSockets with Python (using FastAPI) and Streamlit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Set Up FastAPI WebSocket Server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This code sets up a WebSocket server using &lt;a href="https://fastapi.tiangolo.com/" rel="noopener noreferrer"&gt;FastAPI&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.broadcast(f"Message: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This WebSocket server can handle multiple connections and broadcast messages to all connected clients.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Streamlit Frontend&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s build a real-time application using &lt;a href="https://streamlit.io/" rel="noopener noreferrer"&gt;Streamlit&lt;/a&gt; that connects to the WebSocket server and receives live updates.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import streamlit as st
import asyncio
import websockets

async def websocket_receive():
    uri = "ws://localhost:8000/ws"
    async with websockets.connect(uri) as websocket:
        while True:
            message = await websocket.recv()
            st.write(f"Received: {message}")

st.title("Real-Time WebSocket Client")

if st.button("Connect to WebSocket"):
    st.write("Connected!")
    asyncio.run(websocket_receive())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;: When the user clicks the “Connect to WebSocket” button, the Streamlit frontend establishes a connection with the WebSocket server and listens for messages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Running the Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Run the FastAPI server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;uvicorn server:app --reload
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the Streamlit app:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;streamlit run your_script.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key Steps in Real-Time Communication:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;WebSocket Setup: The WebSocket server runs and accepts connections.&lt;/li&gt;
&lt;li&gt;Streamlit Connection: Streamlit frontend initiates a connection to the WebSocket server.&lt;/li&gt;
&lt;li&gt;Full-Duplex Communication: Both client (Streamlit) and server (FastAPI) can send/receive messages in real-time.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
      <category>datascience</category>
      <category>websocket</category>
      <category>realtimecommunication</category>
    </item>
    <item>
      <title>Synchronous and Asynchronous Programming in Python: Key Concepts and Applications</title>
      <dc:creator>keshavadk</dc:creator>
      <pubDate>Fri, 30 Aug 2024 17:36:55 +0000</pubDate>
      <link>https://dev.to/keshavadk/synchronous-and-asynchronous-programming-in-python-key-concepts-and-applications-28da</link>
      <guid>https://dev.to/keshavadk/synchronous-and-asynchronous-programming-in-python-key-concepts-and-applications-28da</guid>
      <description>&lt;p&gt;&lt;strong&gt;Synchronous Programming&lt;/strong&gt;&lt;br&gt;
In synchronous programming, tasks are executed one after another. Each task must complete before the next one begins. This linear approach is straightforward but can be inefficient, especially when dealing with I/O-bound operations like file reading, network requests, or database queries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import time

def task1():
    print("Starting task 1...")
    time.sleep(2)
    print("Task 1 completed")

def task2():
    print("Starting task 2...")
    time.sleep(2)
    print("Task 2 completed")

def main():
    task1()
    task2()

if __name__ == "__main__":
    main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, task1 must complete before task2 starts. The total execution time is the sum of the time taken by each task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous Programming&lt;/strong&gt;&lt;br&gt;
Asynchronous programming allows multiple tasks to run concurrently, improving efficiency, especially for I/O-bound tasks. Python’s asyncio library provides the necessary tools for asynchronous programming.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import asyncio

async def task1():
    print("Starting task 1...")
    await asyncio.sleep(2)
    print("Task 1 completed")

async def task2():
    print("Starting task 2...")
    await asyncio.sleep(2)
    print("Task 2 completed")

async def main():
    await asyncio.gather(task1(), task2())

if __name__ == "__main__":
    asyncio.run(main())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, task1 and task2 run concurrently, reducing the total execution time to the time taken by the longest task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Potential Applications&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Web Servers and APIs:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Synchronous: Traditional web frameworks like Flask handle requests sequentially. This can be a bottleneck when handling a large number of requests.&lt;/li&gt;
&lt;li&gt;Asynchronous: Frameworks like FastAPI and aiohttp use asynchronous programming to handle multiple requests concurrently, improving throughput and performance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Real-time Messaging Applications:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Synchronous: Handling real-time messages can lead to delays if each message is processed sequentially.&lt;/li&gt;
&lt;li&gt;Asynchronous: Using WebSockets with asynchronous handling (e.g., websockets library) allows for real-time bidirectional communication, enabling high-performance chat applications, live notifications, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Data Processing Pipelines:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Synchronous: Processing large datasets sequentially can be time-consuming.&lt;/li&gt;
&lt;li&gt;Asynchronous: Asynchronous tasks can fetch, process, and store data concurrently, significantly reducing processing time. Libraries like aiohttp and aiomysql can be used for asynchronous HTTP requests and database operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Web Scraping:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Synchronous: Sequentially fetching web pages can be slow and inefficient.&lt;/li&gt;
&lt;li&gt;Asynchronous: Using aiohttp for asynchronous HTTP requests can fetch multiple web pages concurrently, speeding up the web scraping process.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  File I/O Operations:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Synchronous: Reading/writing large files sequentially can block other operations.&lt;/li&gt;
&lt;li&gt;Asynchronous: Asynchronous file I/O operations using aiofiles can improve performance by allowing other tasks to run concurrently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Choosing Between Synchronous and Asynchronous&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use synchronous programming for CPU-bound tasks where the operations are computationally intensive and benefit from running sequentially.&lt;/li&gt;
&lt;li&gt;Use asynchronous programming for I/O-bound tasks where the operations involve waiting for external resources, such as network requests, file I/O, or database queries.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Real-time Messaging Application Example&lt;/strong&gt;&lt;br&gt;
Let’s create a basic real-time messaging application using &lt;a href="https://fastapi.tiangolo.com/" rel="noopener noreferrer"&gt;FastAPI&lt;/a&gt; for the backend and WebSockets for real-time communication. We’ll use &lt;a href="https://streamlit.io/" rel="noopener noreferrer"&gt;Streamlit&lt;/a&gt; for the frontend to display messages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Backend (FastAPI + WebSockets)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1.Install Dependencies:&lt;br&gt;
&lt;code&gt;pip install fastapi uvicorn websockets&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;2.Backend Code (backend.py):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from typing import List

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_message(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_message(data)
    except WebSocketDisconnect:
        manager.disconnect(websocket)

@app.get("/")
async def get():
    return HTMLResponse("""
    &amp;lt;!DOCTYPE html&amp;gt;
    &amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;Chat&amp;lt;/title&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;h1&amp;gt;WebSocket Chat&amp;lt;/h1&amp;gt;
        &amp;lt;form action="" onsubmit="sendMessage(event)"&amp;gt;
            &amp;lt;input type="text" id="messageText" autocomplete="off"/&amp;gt;
            &amp;lt;button&amp;gt;Send&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
        &amp;lt;ul id='messages'&amp;gt;
        &amp;lt;/ul&amp;gt;
        &amp;lt;script&amp;gt;
            var ws = new WebSocket("ws://localhost:8000/ws");
            ws.onmessage = function(event) {
                var messages = document.getElementById('messages');
                var message = document.createElement('li');
                message.appendChild(document.createTextNode(event.data));
                messages.appendChild(message);
            };

            function sendMessage(event) {
                var input = document.getElementById("messageText");
                ws.send(input.value);
                input.value = '';
                event.preventDefault();
            }
        &amp;lt;/script&amp;gt;
    &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
    """)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Frontend (Streamlit)&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Install Dependencies:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install streamlit websocket-client
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Frontend Code (frontend.py):
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import streamlit as st
import asyncio
import threading
from websocket import create_connection, WebSocket

st.title("Real-time Messaging Application")

if 'messages' not in st.session_state:
    st.session_state.messages = []

def websocket_thread():
    ws = create_connection("ws://localhost:8000/ws")
    st.session_state.ws = ws
    while True:
        message = ws.recv()
        st.session_state.messages.append(message)
        st.experimental_rerun()

if 'ws' not in st.session_state:
    threading.Thread(target=websocket_thread, daemon=True).start()

input_message = st.text_input("Enter your message:")

if st.button("Send"):
    if input_message:
        st.session_state.ws.send(input_message)
        st.session_state.messages.append(f"You: {input_message}")

st.subheader("Chat Messages:")
for message in st.session_state.messages:
    st.write(message)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Running the Application&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Start the FastAPI backend:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;uvicorn backend:app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Start the Streamlit frontend:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;streamlit run frontend.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;br&gt;
Backend (backend.py):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The FastAPI app has a WebSocket endpoint at /ws.&lt;/li&gt;
&lt;li&gt;ConnectionManager handles WebSocket connections, broadcasting messages to all connected clients.&lt;/li&gt;
&lt;li&gt;The root endpoint (/) serves a simple HTML page for testing the WebSocket connection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Frontend (frontend.py):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Streamlit app connects to the WebSocket server and listens for incoming messages.&lt;/li&gt;
&lt;li&gt;A separate thread handles the WebSocket connection to prevent blocking the Streamlit app.&lt;/li&gt;
&lt;li&gt;Users can send messages using the input box, which are then sent to the WebSocket server and displayed in the chat.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This example demonstrates a simple real-time messaging application using FastAPI and WebSockets for the backend and Streamlit for the frontend.&lt;/p&gt;

</description>
      <category>python</category>
      <category>fastapi</category>
      <category>streamlit</category>
      <category>websockets</category>
    </item>
  </channel>
</rss>
