<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicolas Bernal on Medium]]></title>
        <description><![CDATA[Stories by Nicolas Bernal on Medium]]></description>
        <link>https://medium.com/@nicolas1009?source=rss-477d76d46418------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Nicolas Bernal on Medium</title>
            <link>https://medium.com/@nicolas1009?source=rss-477d76d46418------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:54:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicolas1009/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GraphQL vs REST: Understanding Core Differences]]></title>
            <link>https://nicolas1009.medium.com/graphql-vs-rest-understanding-core-differences-7e030ebc001a?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e030ebc001a</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Mon, 12 May 2025 23:21:05 GMT</pubDate>
            <atom:updated>2025-05-13T09:46:09.100Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>To truly succeed in any technical field, you must deeply understand its fundamentals — those obvious principles we rarely pause to examine. This is especially critical when comparing <strong>REST</strong> and <strong>GraphQL</strong>, two approaches to API design. Let’s break them down.</p><h3>REST APIs: An Architectural Guide</h3><p>REST (Representational State Transfer) is <strong>an architectural style</strong>, not a specific technology. It provides principles for designing APIs, defined by Roy Fielding. If you follow these rules, you’re building a <strong>RESTful</strong> API.</p><h4>Key Principles of REST</h4><ol><li><strong>Statelessness</strong>: Every request must contain all necessary information. The server retains no client state between requests.</li><li><strong>Unique Resource Identifiers</strong>: Each resource (e.g., user, article) has a distinct URI (e.g., GET /users/123, GET /articles/456).</li><li><strong>Standard HTTP Verbs</strong>: Use GET, POST, PUT, PATCH, DELETE, etc., according to their semantic purposes.</li></ol><p>As we can see, REST revolves around following principles. If you adhere to them, you’re building a RESTful API. However, REST is not a specific technology — it’s a guideline. You retain flexibility to:</p><ul><li><strong>Choose your backend stack</strong> (language, framework — e.g., Python with Flask or FastAPI).</li><li><strong>Select which HTTP verbs</strong> to implement (only those required by your endpoints, not all).</li><li><strong>Structure resources and URIs</strong> according to REST’s rules.</li></ul><pre>from flask import Flask, jsonify, request<br><br>app = Flask(__name__)<br><br>data = {<br>    &quot;users&quot;: {<br>        &quot;123&quot;: {&quot;name&quot;: &quot;Alice&quot;, &quot;premium&quot;: True},<br>        &quot;456&quot;: {&quot;name&quot;: &quot;Bob&quot;, &quot;premium&quot;: False}<br>    }<br>}<br><br>@app.route(&#39;/users/&lt;user_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_user(user_id):<br>    user = data.get(&quot;users&quot;).get(user_id)<br>    if user:<br>        return jsonify(user), 200<br>    return jsonify({&quot;error&quot;: &quot;User not found&quot;}), 404<br><br>@app.route(&#39;/users&#39;, methods=[&#39;POST&#39;])<br>def create_user():<br>    user = request.json<br>    user_id = str(len(data[&quot;users&quot;]) + 1)<br>    data[&quot;users&quot;][user_id] = user<br>    return jsonify({&quot;id&quot;: user_id}), 201<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><h4>Why REST Shines</h4><ul><li><strong>Simplicity</strong>: Easy to implement (e.g., Python + Flask/FastAPI).</li><li><strong>Flexibility</strong>: Choose your backend stack, framework, and required HTTP verbs.</li><li><strong>Caching</strong>: CDNs natively cache GET requests, improving performance.</li><li><strong>Readability</strong>: URIs and verbs make endpoints self-explanatory (e.g., DELETE /users/123 clearly deletes a user).</li></ul><h4>REST’s Limitations</h4><ul><li><strong>Endpoint Proliferation</strong>: As systems scale, you’ll need more endpoints (e.g., GET /v1/users, GET /v2/users), complicating maintenance. You might start with just a few, but eventually end up managing <strong>100+ endpoints</strong> (though extreme, it does occur).</li><li><strong>Over-fetching</strong>: Clients often receive unnecessary data (e.g., fetching an entire user object when only id and subscription_type are needed).</li><li><strong>Multiple Requests</strong>: Complex data might require chained calls (e.g., GET /writers/123 → GET /articles/123), increasing latency. This approach depends heavily on <strong>how the data is structured</strong> (common in traditional SQL databases, as discussed later). While this example requires just two calls, real-world systems can demand <strong>dozens of chained requests</strong>, significantly increasing latency. Each client-side request adds network overhead, slowing down the system.</li></ul><h3>GraphQL: A Query Language for APIs</h3><p>GraphQL emerged to address REST’s limitations. Unlike REST, it’s <strong>a concrete technology</strong> (a query language) that works over HTTP, WebSockets, or other protocols (but is used mainly over HTTP)</p><p><strong>So, what exactly is GraphQL?</strong></p><p>At its core, GraphQL is a <strong>query language</strong> (similar to SQL) designed for fetching data from databases or APIs. While it <em>does</em> involve additional components like <strong>schemas</strong> (to define data structures) and <strong>resolvers</strong> (to fetch data), the foundational idea is simple: <strong>let clients request exactly what they need</strong>, nothing more.</p><h4>How GraphQL Works</h4><ul><li><strong>Single Endpoint</strong>: All interactions use one endpoint (e.g., /graphql).</li><li><strong>Query Language</strong>: Clients request <strong>exactly</strong> what they need in one call (no over-fetching).</li><li><strong>POST-Centric</strong>: Most operations use POST, even for reads (unlike REST’s GET-based caching).</li></ul><h4><strong>Everything is POST</strong></h4><p>In GraphQL, when used over HTTP, almost every operation is sent via the POST method (Technically could be use GET for simple queries but is not common). The reason to use POST is for practice, since queries could be long and mutations can modify data (not secure for GET). This can seem a bit counterintuitive at first, especially if you’re used to REST, where different HTTP verbs (GET, POST, PUT, DELETE) have specific semantic meanings. Technically, POST can be used for GET, UPDATE and DELETE.</p><p>So why not just use POST for everything in REST as well? Here are a few reasons:</p><ol><li><strong>REST Principles:</strong> RESTful design encourages the use of specific HTTP methods to clearly indicate the intent of each request, making the API more predictable and easier to understand.</li><li><strong>Caching:</strong> HTTP GET requests are natively cacheable by browsers and CDNs, while POST requests are not. This can significantly improve performance for read-heavy APIs.</li><li><strong>Idempotency:</strong> In REST, methods like GET, PUT, and DELETE are expected to be idempotent, meaning multiple identical requests have the same effect as a single request. POST, on the other hand, is not guaranteed to be idempotent, which can lead to unintended side effects if used improperly.</li></ol><p>However, GraphQL is designed as a query language, not just an API specification. It prioritizes flexibility and efficiency over strict HTTP semantics. This is why it can use a single POST endpoint to handle all types of data operations, including data fetching, updating, and deleting.</p><h4>No Multiple Endpoints</h4><p>In GraphQL, you don’t implement multiple endpoints with different HTTP verbs like you do in REST. Instead, you have a <strong>single</strong> endpoint (e.g., /graphql) that handles all operations.</p><p><strong><em>Small example</em></strong>:</p><pre># REST. <br># Get all the post from a user, requires two calls with Rest.<br><br>GET /users/123          → Usuario<br>GET /users/123/posts    → Posts<br><br># 2 HTTP calls, possible over-fetching problems.</pre><pre># GraphQL<br><br>POST /graphql<br><br>query GetUserAndPosts {<br>  user(id: 123) { name }<br>  posts(userId: 123) { title }<br>}<br><br><br># Just one call</pre><p>Sounds like magic – one endpoint for everything? Yes, but it’s not magic. Instead of defining multiple endpoints, you define <strong>schemas</strong>, <strong>resolvers</strong>, <strong>queries</strong>, and <strong>mutations</strong> to handle various data operations.</p><h4>Schemas</h4><p>Think of schemas as <strong>blueprints</strong> (similar to abstract classes in Python). They define:</p><ul><li>Available operations (queries, mutations).</li><li>Data structures (types, fields, and relationships).</li></ul><h4>Queries vs Mutations</h4><ul><li><strong>Queries</strong>: Read-only operations (analogous to GET in REST).</li><li><strong>Mutations</strong>: Write operations (analogous to POST, PUT, DELETE).</li></ul><pre># Schema.py<br><br>import strawberry<br><br>@strawberry.type<br>class Post:<br>    id: int<br>    title: str<br><br>@strawberry.type<br>class User:<br>    id: int<br>    name: str<br>    posts: list[Post]<br><br>@strawberry.type<br>class Query:<br>    @strawberry.field<br>    def user(self, id: int) -&gt; User:<br>        # Lógica implementada en resolvers.py<br>        raise NotImplementedError(&quot;Resolver no implementado&quot;)<br><br>schema = strawberry.Schema(query=Query)</pre><h4>Resolvers</h4><p>Resolvers are the <strong>implementation layer</strong> of the schema. They:</p><ul><li>Fetch data for queries (e.g., from a database).</li><li>Execute logic for mutations (e.g., creating/deleting records).</li></ul><pre>from .schema import User, Post<br><br>class UserResolver:<br>    def resolve_user(self, id: int) -&gt; User:<br>        # Example with statuc data (use DB/API in prod)<br>        return User(<br>            id=id,<br>            name=&quot;Ana&quot;,<br>            posts=[Post(id=1, title=&quot;Hello GraphQL&quot;)]<br>        )</pre><p>In general, the workflow in GraphQL would be like this:</p><pre>Client GraphQL (Query/Mutation)<br>        ↓<br>Schema (Validate request agains the data type and operations defined)<br>        ↓<br>Execute resolvers<br>        ↓<br>Combine and return results</pre><p>There are more key concepts related to GraphQL, but this article is focused on explaining what GraphQL is and how it differs from REST, rather than being a full course on how to write or implement queries. For now, these are the most relevant concepts to understand this technology.</p><p>One last important thing: in REST, resources and critical parameters are typically included in the URI (e.g., GET /user/ID), making the route structure essential. In GraphQL, however, the user ID and other parameters are specified directly in the query, not the URL.</p><h4>GraphQL is amazing, everything is perfect!!! Not exactly:</h4><p>GraphQL is a powerful tool but is not the answer for everything. It comes with its own challenges.</p><p><strong>GraphQL’s Challenges</strong></p><ol><li><strong>Complexity</strong>: Requires schemas, resolvers, and client coordination. Is more complex to implement than a REST.</li><li><strong>Caching</strong>: POST breaks HTTP caching, CDNs don’t offer caching from GraphQL (due POST, by default HTTP offers cache for GET); solutions like persisted queries or client-side caching are needed.</li><li><strong>N+1 Problem</strong>: <strong>N+1 Problem:</strong> This problem occurs when a single initial query leads to <strong>N</strong> additional database queries. For example, an initial query to get 100 users might trigger 100 separate database calls to retrieve their associated articles (100 users 100 queries, in total 101 queries). <strong>Fix:</strong> Use a <strong>DataLoader</strong> to batch these requests and implement caching strategies to reduce the number of database round trips.</li><li><strong>Idempotency</strong>: Unlike REST’s GET/DELETE, GraphQL relies on POST, so design mutations carefully (e.g., use unique IDs to avoid duplicate operations).</li></ol><h4>Idempotency Explained</h4><p>A system or operation is <strong>idempotent</strong> if executing it multiple times <strong>always produces the same result</strong>. For example:</p><ul><li>In mathematics, the operation <strong>2 + 2</strong> is idempotent because it always equals <strong>4</strong>, regardless of how many times it’s executed.</li><li>In HTTP, the <strong>GET</strong> method is idempotent: calling GET /users/123 ten times will return the same user data each time.</li><li>Similarly, <strong>DELETE</strong> is idempotent: deleting a user with DELETE /users/123 once has the same effect as doing it repeatedly.</li></ul><h4>Why POST Isn’t Idempotent</h4><p>The <strong>POST</strong> method, however, is <strong>not idempotent</strong>. For example:</p><ul><li>Calling POST /users/Ana 100 times would create <strong>100 separate users</strong> named &quot;Ana&quot; in the database.</li></ul><h4>GraphQL’s Idempotency Challenge</h4><p>Since GraphQL primarily uses <strong>POST</strong> for all operations (even reads), idempotency <strong>must be handled explicitly</strong> by developers. For example:</p><ul><li>Mutations (writes) should be designed to avoid duplicate side effects (e.g., using unique IDs or checks).</li></ul><h3>REST vs GraphQL: When to Use Each</h3><p><strong>Choose REST</strong> for:</p><ul><li>Simple CRUD apps.</li><li>Projects needing CDN caching.</li><li>Teams prioritizing quick setup.</li></ul><p><strong>Choose GraphQL</strong> for:</p><ul><li>Complex systems with nested data.</li><li>Mobile apps requiring minimal payloads.</li><li>APIs where client flexibility is critical.</li></ul><h3>Final Thoughts</h3><p><strong>Start with REST</strong> for simplicity and caching.</p><p><strong>Adopt GraphQL</strong> when facing:</p><ul><li>Endpoint sprawl.</li><li>Over-fetching.</li><li>Mobile latency issues.</li></ul><p>GraphQL’s power comes with complexity — evaluate your team’s capacity before diving in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e030ebc001a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes vs. AWS ECS: A Comprehensive Guide]]></title>
            <link>https://nicolas1009.medium.com/kubernetes-vs-aws-ecs-a-comprehensive-guide-b6c9dfc4f6bc?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6c9dfc4f6bc</guid>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 18:55:54 GMT</pubDate>
            <atom:updated>2025-04-04T09:32:53.333Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Kubernetes</strong> and <strong>AWS ECS</strong> (Elastic Container Service) are both tools for orchestrating containers (e.g., Docker), virtual machines, and serverless workloads. However, they differ in ownership and architecture:</p><ul><li><strong>Kubernetes</strong> is <strong>open-source</strong>, meaning it works across any cloud or on-premises environment.</li><li><strong>AWS ECS</strong> is a <strong>proprietary service</strong> managed by Amazon Web Services (AWS), designed to integrate seamlessly with AWS infrastructure.</li></ul><p>While they share similar goals, their architectures and workflows differ significantly.</p><p><strong><em>Note:</em></strong><em> On AWS, you can also deploy Kubernetes clusters using </em><strong><em>AWS EKS</em></strong><em> (Elastic Kubernetes Service) — a managed service that simplifies Kubernetes deployment and maintenance with native integration of AWS features, enterprise-grade support, and a fully managed control plane. Also, I’m not going to dive into costs.</em></p><p><strong><em>Comparison:</em></strong></p><pre>+---------------------+--------------------------------+--------------------------------+<br>|      Category       | Kubernetes                     | AWS ECS                        |<br>+---------------------+--------------------------------+--------------------------------+<br>| Architecture        | Master-worker (Control Plane + | AWS-managed cluster (no master |<br>|                     | Workers). Self-managed*        | node). Options: Fargate        |<br>|                     | (*Except in EKS).              | (serverless) or EC2.           |<br>+---------------------+--------------------------------+--------------------------------+<br>| Complexity          | High (YAML, CLI, concepts      | Moderate (AWS Console/CLI      |<br>|                     | like Pods, Services).          | integration, abstraction).     |<br>+---------------------+--------------------------------+--------------------------------+<br>| Scalability         | Horizontal Pod Autoscaler      | AWS Auto Scaling (CloudWatch   |<br>|                     | (custom metrics).              | integration).                  |<br>+---------------------+--------------------------------+--------------------------------+<br>| Cloud Integration   | Multi-cloud (requires setup)   | Native AWS integration (IAM,   |<br>|                     |                                | ALB, VPC, CloudWatch).         |<br>+---------------------+--------------------------------+--------------------------------+<br>| Use Cases           | Multi-cloud, complex apps      | AWS-centric workloads,         |<br>|                     | (service mesh, custom CNI).    | serverless (Fargate), AWS-native|<br>|                     |                                | CI/CD pipelines.               |<br>+---------------------+--------------------------------+--------------------------------+<br>| Tools               | Helm, Istio, Prometheus.       | AWS CodePipeline, CloudForma-  |<br>|                     |                                | tion, X-Ray integration.       |<br>+---------------------+--------------------------------+--------------------------------+<br>| Maintenance         | High (unless using EKS).       | Low (especially with Fargate). |<br>+---------------------+--------------------------------+--------------------------------+</pre><h3>Kubernetes Architecture</h3><p>Kubernetes uses a <strong>master-worker node model</strong>:</p><p><strong>Master Node (Control Plane)</strong>: The “brain” of the cluster, responsible for managing operations.</p><p><strong>Control Plane components:</strong></p><ul><li><strong>API Server</strong>: Handles commands (e.g., from kubectl) and external communication.</li><li><strong>ETCD</strong>: A secure Key-Value database storing cluster configuration (e.g., desired pod count, secrets, metadata). <em>Critical Note</em>: If etcd fails, the cluster loses its <em>desired state</em> (e.g., how many pods should run), but <strong>running pods are unaffected</strong>.</li><li><strong>Scheduler</strong>: Assigns pods to worker nodes based on resource availability.</li><li><strong>Controller Manager</strong>: Ensures the cluster matches the desired state (e.g., restarting failed pods).</li></ul><p><strong>Worker Nodes</strong>: Machines that run your applications. Each worker includes:</p><ul><li><strong>kubelet</strong>: An agent that manages pods (starting/stopping containers).</li><li><strong>kube-proxy</strong>: Handles network rules (e.g., routing traffic between pods).</li><li><strong>Container Runtime</strong>: Software like Docker or containerd to execute containers.</li></ul><pre><br>                            +-----------------------+<br>                            |      Master Node      |<br>                            |  (Control Plane)      |<br>                            +-----------------------+<br>                            |  - API Server         |<br>                            |  - etcd               |<br>                            |  - Scheduler          |<br>                            |  - Controller Manager |<br>                            +----------+------------+<br>                                       |<br>                                       | (API Calls, Updates)<br>                                       v<br>                +-----------------------------------------------+<br>                |               Worker Nodes                    |<br>                +-----------------------------------------------+<br>                |                                               |<br>    +-----------+---------+                         +-----------+---------+<br>    |     Worker Node 1    |                         |     Worker Node 2    |<br>    +----------------------+                         +----------------------+<br>    | - Kubelet            |                         | - Kubelet            |<br>    | - Kube-proxy         |                         | - Kube-proxy         |<br>    |                      |                         |                      |<br>    | Pods:                |                         | Pods:                |<br>    |  ▢ [Container A]     |                         |  ▢ [Container X]    |<br>    |  ▢ [Container B]     |                         |  ▢ [Container Y]    |<br>    +----------------------+                         +----------------------+</pre><p>A typical workflow when is deployed pods in Kubernetes looks like:</p><pre>Usuario → kubectl apply (Deployment YAML)  <br>                ↓  <br>        API Server → ETCD (guarda estado deseado)  <br>                ↓  <br>        Deployment Controller crea un ReplicaSet  <br>                ↓  <br>        ReplicaSet crea N pods  <br>                ↓  <br>        Scheduler asigna pods a nodos  <br>                ↓  <br>        kubelet (en workers) ejecuta los contenedores</pre><h3>Core Kubernetes Concepts</h3><p><strong>1.Pod</strong></p><ul><li><strong>Smallest unit</strong>: A group of containers sharing storage and network (e.g., a web app + logging sidecar).</li><li><strong>Ephemeral</strong>: Pods are temporary — data inside them is lost if they restart.</li></ul><p><strong>2. Service</strong></p><p>Acts as a stable endpoint for pods. Pods needs to talk beetween them. Even if pods restart, the Service ensures traffic reaches them.</p><ul><li><strong>Types</strong>:</li><li>ClusterIP (internal access only).</li><li>NodePort (exposes a port on the worker node).</li><li>LoadBalancer (integrates with cloud load balancers).</li><li><strong>Note</strong>: For external HTTP/HTTPS traffic, use <strong>Ingress</strong> (not Services).</li></ul><p><strong>3. ReplicaSet</strong></p><ul><li>Ensures a specified number of pods are always running (e.g., if a pod crashes, the ReplicaSet recreates it).</li><li><strong>Replaces Replication Controllers</strong>: Offers more advanced pod selection rules (e.g., matchLabels and matchExpressions).</li></ul><p><strong>4. Deployment</strong></p><ul><li>Manages ReplicaSets and enables features like:</li><li>Zero-downtime updates (<em>rolling updates</em>).</li><li>Rollbacks to previous versions.</li><li>Version history tracking.</li><li><strong>Why use it even for a single pod?</strong> Simplifies updates and rollbacks.</li></ul><p><strong>5. Namespaces</strong></p><ul><li>Isolates resources (e.g., pods, services) into logical partitions (e.g., dev, prod).</li><li><strong>Global resources</strong> (e.g., Nodes) exist outside namespaces.</li></ul><p><strong>6. ConfigMaps:</strong> Inject non-sensitive configuration (e.g., environment variables) into pods.</p><p><strong>7. Secrets</strong>: Store sensitive data (e.g., passwords) in base64-encoded format.</p><p><strong>8. Volumes</strong></p><ul><li>Provide persistent storage for pods (e.g., database files stored on AWS EBS).</li><li><strong>Example</strong>: A pod running a database uses a volume to ensure data survives pod restarts.</li></ul><p><strong>9. Ingress: </strong>Manages external HTTP/HTTPS access to internal services.</p><h3>AWS ECS Architecture</h3><p>As mentioned earlier, ECS and Kubernetes achieve similar goals but use different architectural workflows. From a user’s perspective, the key difference is that ECS <strong>does not require a master node</strong> (AWS fully manages the control plane). As a result, configuring and maintaining an ECS cluster is simpler than managing Kubernetes. While ECS operates differently from Kubernetes, it’s possible to draw parallels and identify equivalents between them.</p><p><strong>Components:</strong></p><ol><li><strong>ECS Cluster</strong>: A logical group of resources (EC2 instances or serverless Fargate tasks). It’s equivalent to a Kubernetes Cluster.</li><li><strong>Task Definition</strong>: A blueprint specifying containers to run (image, CPU/memory, networking).</li><li><strong>Task</strong>: A running instance of a Task Definition (similar to a Kubernetes pod).</li><li><strong>Service</strong>: Ensures a specified number of tasks are always running (similar to Kubernetes Deployments).</li></ol><p>ECS flow:</p><pre>[Task Definition] → [Service] → [Tareas en Fargate/EC2]  <br>                          ↓  <br>                  [ALB/NLB] → [Usuarios]  </pre><h4>Key AWS ECS Concepts</h4><ol><li><strong>Task Definition</strong></li></ol><ul><li>Specifies container images, CPU/memory, networking, and volumes (similar to a Kubernetes pod + deployment).</li></ul><ol><li><strong>Task</strong></li></ol><ul><li>A running instance of a Task Definition (somilar to a pod).</li><li><strong>Fargate</strong>: Serverless option (no EC2 instances to manage).</li><li><strong>EC2</strong>: Tasks run on EC2 instances (similar to Kubernetes worker nodes).</li></ul><ol><li><strong>Service</strong></li></ol><ul><li>Maintains the desired number of tasks (e.g., 3 replicas) and handles deployments.</li><li><strong>Equivalent in Kubernetes</strong>: Deployment + Service.</li></ul><ol><li><strong>IAM Roles &amp; Security Groups</strong></li></ol><ul><li><strong>IAM Roles</strong>: Assign permissions to tasks (e.g., access S3 buckets).</li><li><strong>Security Groups</strong>: Act as a firewall for tasks (network-level security).</li></ul><h4>Unique Components of ECS</h4><ol><li><strong>Capacity Providers</strong>:</li></ol><ul><li>Define how resources are provisioned (e.g., Fargate, EC2 Spot/On-Demand instances).</li></ul><ol><li><strong>Service Discovery</strong>:</li></ol><ul><li>Integrates with <strong>AWS Cloud Map</strong> for internal DNS management (similar to CoreDNS in Kubernetes).</li></ul><ol><li><strong>AWS Code Integration</strong>:</li></ol><ul><li>Native CI/CD workflows using <strong>AWS CodePipeline</strong> and <strong>CodeDeploy</strong>.</li></ul><h3>Which Should You Choose?</h3><p><strong><em>While cost considerations are critical when choosing a platform (and should always be analyzed), let’s focus first on technical fit:</em></strong></p><p>This is a common question, and the answer is equally common: <em>it depends on your needs</em>. Both Kubernetes and ECS are powerful tools, but I’ll avoid giving a purely generic response.</p><ul><li><strong>Kubernetes</strong> is open-source, making it cloud-agnostic and adaptable to various providers and projects. However, it requires significant maintenance and configuration effort (though AWS EKS simplifies this).</li><li><strong>ECS</strong>, on the other hand, sacrifices some flexibility for simplicity. With ECS — especially Fargate — you’ll spend less time configuring and maintaining infrastructure.</li></ul><p>To put it bluntly: If you prioritize <strong>total control</strong>, choose Kubernetes. If you want <strong>minimal upkeep</strong>, choose ECS.</p><p>Let’s be honest — if you’re considering ECS, you likely want something easy to configure, low-maintenance, and serverless-friendly. My advice:</p><ul><li>If your architecture and use case are suited for <strong>serverless</strong> (e.g., event-driven workloads), go with <strong>ECS + Fargate</strong>. It’s simpler to manage and scales seamlessly. (Also, if your architecture is fully in AWS, ECS is a good option)</li><li>If you need <strong>full control</strong> over infrastructure (e.g., complex on-premises systems), <strong>Kubernetes</strong> is the better choice.</li></ul><p><strong>Don’t forget compatibility</strong>:</p><ul><li>Some tools (e.g., Istio for service mesh, Helm for package management) work natively with Kubernetes but aren’t supported by ECS. Always verify if your required tools integrate with your chosen platform.</li></ul><p><strong>A note on ECS + EC2</strong>:</p><ul><li>While ECS can run on EC2 instances, this setup often defeats the purpose of simplicity. If you’re managing EC2 servers anyway, Kubernetes (e.g., via EKS) offers a richer ecosystem and flexibility. Reserve ECS for its <strong>serverless strength</strong> (Fargate).</li></ul><p>Of course, this is just my opinion!</p><p><strong><em>One last thought:</em></strong></p><p><em>“Of course, this landscape evolves rapidly. For example, AWS has recently enhanced integration between AWS EKS (its managed Kubernetes service) and Fargate, blurring the lines between ECS and Kubernetes in some scenarios. While this article provides a foundational technical comparison, always consult the latest AWS documentation or Kubernetes release notes — in the cloud-native world, today’s ‘best practice’ may be tomorrow’s legacy approach.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6c9dfc4f6bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Is Your Computer Really Random?How]]></title>
            <link>https://nicolas1009.medium.com/is-your-computer-really-random-4f633c996d7b?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f633c996d7b</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[mersenne-twister]]></category>
            <category><![CDATA[random]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 00:59:33 GMT</pubDate>
            <atom:updated>2025-03-20T01:55:58.587Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>“Is Your Computer <em>Really</em> Random?How Python’s ‘Random’ Library Actually Works (Spoiler: It’s Not Random!)”</strong></h3><p>A few weeks ago, after some budget cuts at work, I suddenly found myself unemployed. While I wait for my next project, I’ve been catching up on video games I’d missed during my busy career. But while browsing gaming forums, I stumbled into a heated debate: fans were arguing whether “procedural generation” in games is the same as “randomness.” Spoiler: It’s <em>not</em> exactly the same, but in practice is the same… but today, let’s talk about <strong>true randomness</strong> and why your computer can’t actually do it.</p><h3>Why Computers Can’t Be Truly Random</h3><p>First, let’s define “random.” This could pretty Philosophic, but we can say that true randomness means something happens spontaneously, without any pattern or predictability. Think of lightning strikes or dice rolls — they’re chaotic and impossible to guess beforehand.</p><p>But computers? They’re the <em>opposite</em> of chaos. They follow strict algorithms (step-by-step instructions) to do <em>everything</em>. Even when your laptop seems to “choose” a number between 1 and 100, it’s not truly random — it’s <strong>pseudorandom. </strong>(I’m not talking quantum computers)</p><p><em>(Fun fact: Humans aren’t great at randomness either! We’re biased toward patterns, like picking “7” more often than “37” in a 1–100 guess.)</em></p><h3>How Does Python’s Random Library Work?</h3><p>If computers can’t be random, how does Python’s random.randint(1, 100) give us a “random” number? The answer lies in <strong>pseudorandom number generators (PRNGs)</strong>.</p><h4>The Secret Sauce: The Mersenne Twister</h4><p>Python’s random library uses an algorithm called the <strong>Mersenne Twister</strong> — named after <strong>Mersenne prime numbers</strong> &lt;prime numbers of the form (2^n)-1&gt; and the <strong>twist </strong>due the algorithm makes a “twist” operation it performs once the initial batch of generated numbers is exhausted. Here’s how it works in simple terms:</p><ol><li><strong>It Starts With a Seed</strong><br>Every PRNG needs a starting point called a <strong>seed</strong>. If you don’t set one (e.g., random.seed(123)), Python uses your computer’s clock time (in seconds) as the default seed.<br><em>Why does this matter?</em> If two people use the <em>same seed</em>, they’ll get the <em>same sequence</em> of “random” numbers!</li><li><strong>Generating 624 “Random” Numbers</strong><br>The Mersenne Twister creates 624 numbers using complex <em>deterministic</em> math (like shifting bits in binary code). These numbers look random but follow a hidden pattern.</li><li><strong>The “Twist”</strong><br>Once all 624 numbers are used, the algorithm “twists” them (rearranges bits) to create a new batch. This cycle repeats forever.</li><li><strong>Tempering: Making Numbers “Look Random”</strong><br>Before spitting out a number, the algorithm applies a <strong>tempering</strong> step. This scrambles the bits further (using more bits math!) to hide patterns and make the numbers <em>appear</em> more random.</li><li><strong>Adjusting to Your Range</strong><br>Finally, Python converts one of these numbers to your desired range. For example, if you ask for 1–100, it does something like number = (generated_number % 100) + 1.</li></ol><pre>+-------------------+     +-----------------------+<br>|      SEED         |     |  State Array (624 núm)|<br>| (Ej: 1638284615)  |----&gt;| [2147, 1051, 4071,...]|<br>+-------------------+     +----------+------------+<br>                                     |<br>                                     | TWIST<br>                                     v<br>+-------------------+     +----------+------------+<br>|   Tempering       |&lt;----| Shifted Bits /XOR     |<br>| (Bits operations )|     | and twisted           |<br>+-------+-----------+     +----------+------------+<br>        |<br>        v<br>+-------------------+<br>|  Final Number     |<br>| (Ej: 82)          |<br>+-------------------+</pre><h3>Pseudorandom ≠ Random</h3><p>These numbers are <strong>pseudorandom</strong> — they <em>look</em> random but are 100% predictable if you know the seed. For example:</p><pre>import random<br><br>random.seed(42)  # Fix the seed<br>print(random.randint(1, 100))  # Output: 82 (every time!)</pre><p>This predictability makes PRNGs great for games or simulations but <strong>dangerous for passwords or encryption</strong>, where true randomness is critical.</p><p>Unless you have a specific strategy, it’s recommended to use the default seed (based on the UNIX clock in seconds plus system information). While technically predictable, the seed’s length and the fact that it changes every millisecond make it nearly impossible — though not entirely impossible — to determine the sequence of numbers. For example, if an attacker knows the approximate time when the script was executed, they could generate possible seeds and use a brute-force attack to guess the sequence.</p><pre>import random<br><br>print(random.randint(1, 100))</pre><p>You can inspect the Mersenne Twister’s internal state (the 624 integers), you can use getstate(). Here’s an example:</p><pre>import random<br><br>random.seed(123)<br>state = random.getstate()<br><br># The matrix state is the SECOND element in the tuple (index 1)<br>matrix_state = state[1]<br><br># First 3 elements of the matrix:<br>print(&quot;Matrix state (first 3 elements):&quot;, matrix_state[:3])</pre><p><strong>Output:</strong><br>Matrix state (first 3 elements): [2147483648, 1051550459, 407192412]</p><p><strong>Why this matters:</strong><br>This is another reason to use the default seed (based on the UNIX timestamp in seconds + system-specific data) since changes every second. While this makes sequences <em>harder</em> to predict, <strong>never use </strong><strong>random for passwords or security tokens</strong>.</p><pre># Theoric Example of force attack (not executable)<br>import random  <br>approximate_time = 1717020000  # Timestamp UNIX approx  <br>for seed in range(approximate_time - 1000, approximate_time + 1000):  <br>    random.seed(seed)  <br>    if random.randint(1, 100) == guessed_number:  <br>        print(&quot;¡seed fiding!&quot;, seed)  </pre><p>For sensitive tasks, use Python’s secrets library instead.</p><h3>When Should You Care?</h3><ul><li><strong>Good for Games/ML</strong>: The Mersenne Twister is perfect for shuffling playlists, generating game levels, or splitting datasets in machine learning.</li><li><strong>Bad for Security</strong>: Never use random for passwords, encryption keys, or tokens. Use Python’s secrets library instead—it relies on true randomness from your OS.</li></ul><h3>The Big Takeaway</h3><p>Computers are terrible at chaos, but clever algorithms like the Mersenne Twister <em>simulate</em> randomness well enough for most tasks. Just remember: if you need true unpredictability (like in cryptography), pseudo-randomness won’t cut it! Use <a href="https://docs.python.org/3/library/secrets.html">secrets</a> library instead.</p><p><em>P.S. Quantum computers might change this someday — they can harness real quantum randomness. But for now, your laptop stays a “random faker.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f633c996d7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Python Slow? Well, Yes and No. C Extensions to the Rescue.]]></title>
            <link>https://nicolas1009.medium.com/is-python-slow-well-yes-and-no-c-extensions-to-the-rescue-956c5de5d069?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/956c5de5d069</guid>
            <category><![CDATA[c-extension]]></category>
            <category><![CDATA[cython]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 02:42:40 GMT</pubDate>
            <atom:updated>2025-02-26T16:35:19.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is widely used today and has become extremely popular. Part of its popularity comes from the fact that people outside of traditional software development also use it. Python is my main day-to-day tool (though not the only one), but like everything else, it’s not perfect. It has its pros and cons.</p><p>When you talk to other tech enthusiasts about Python’s disadvantages, the most common point you’ll hear is: “Python is slow,” or “Python’s performance isn’t the best.” This criticism is pretty generic but still holds some truth. The reality, however, is more nuanced. Let’s dive into why Python can appear “slow” and how C extensions can help us.</p><h4>Why Can Python Be Considered “Slow”?</h4><p>In a previous <a href="https://medium.com/@nicolas1009/how-python-works-from-hello-world-to-electric-signals-a7111835f6fc">article</a>, we discussed the entire process that happens when Python code is executed. In summary, Python goes through these steps:</p><ol><li><strong>Source Code</strong></li><li><strong>Lexical Analysis</strong> (tokenizing)</li><li><strong>Syntax Analysis</strong> (creating an Abstract Syntax Tree, or AST)</li><li><strong>Bytecode Compilation</strong></li><li><strong>Bytecode Execution</strong> (in the Python Virtual Machine, PVM)</li><li><strong>Operating System Calls</strong></li><li><strong>Assembly Instructions</strong></li><li><strong>Machine Code</strong></li><li><strong>Electrical Signals (CPU level)</strong></li></ol><p>For something simple like print(&quot;Hello World&quot;), all these steps happen very quickly, especially on modern hardware. So for typical input/output operations, database queries, API calls, or standard business logic, it’s not a big deal that code has to pass through the PVM.</p><p>However, if you need to work with very large numbers or do CPU-intensive computations, Python’s performance limitations become clearer. Imagine you have a loop adding up numbers from 0 to 100,000.</p><pre>total = 0<br>for i in range(100001):<br>    total += i<br><br>print(&quot;The sum from 0 to 100,000 is:&quot;, total)</pre><p>While the tokenization, parsing, and bytecode compilation happen only once, the PVM needs to execute the resulting bytecode 100,000 times. That extra overhead for each iteration can make Python look slower in these scenarios.</p><p>From all of this we can say that pure Python is “slow” mainly because the code needs to pass through Python Virtual Machine (PVM).</p><p>But what if there’s a way to skip the PVM entirely for parts of our code? The good news is that there is — one such method is to use <strong>C extensions</strong>.</p><h4>What Is a C Extension?</h4><p>A C extension is essentially compiled C code that can be imported and used within a Python program. Since the Python interpreter itself is written in C, these extensions can run closer to the hardware and often achieve better performance. They also give you access to system-level (native) libraries, which are typically written in C or C++.</p><h4>Why Is This Faster Than Pure Python?</h4><p>When you import a module and Python detects it’s a C extension (for example, a .so file on Linux or a .pyd file on Windows), it skips tokenization, parsing, and bytecode compilation for that code. Instead of running bytecode on the PVM, the extension runs compiled C code directly, which leads to a significant speed boost.</p><h4>How Do You Build a C Extension?</h4><p>There are two main ways:</p><ol><li><strong>Write the extension directly in C</strong></li><li><strong>Use Cython</strong>, which lets you write code in a Python-like syntax and compiles it down to C.</li></ol><p><strong>Key Terms</strong>: Python.h and PyObject*</p><p>Before going further, there are two important concepts to be aware of:</p><ul><li><strong>Python.h</strong>: This header file exposes the Python/C API(Python talks with C using an API). It provides functions for creating Python objects (for example, PyList_New()), running Python code (PyRun_SimpleString()), handling exceptions (PyErr_SetString()), and managing memory (Py_INCREF / Py_DECREF), among others. Its like a bridge between Python Objects and C objects.</li><li><strong>PyObject*</strong>: We can say that Python is an elegant layer than envelop a C core. This is the core C type that represents any Python object at the C level. Remember, in Python everything is an object, and each Python object corresponds to a structure in C. PyObject is the Pointer that make relations between Python Objects and C Objects. For instance:</li></ul><pre>List() -&gt; PyListObject -&gt; PyList_New(), PyList_Append()</pre><p>All this is more complex and bigger than just this, but as starting point I think we can understand what is <strong>PyObject*</strong> and <strong>Python.h</strong>.</p><p>Ok nice, but why is this important?</p><p>Writing a C extension directly in C means managing memory and dealing with PyObject* and Python.h manually, which can be tedious—especially if you’re not familiar with C.</p><h4>Writing a C Extension in Cython</h4><p><strong>Cython</strong> simplifies this process considerably. Cython code looks very much like Python but compiles to C, offering performance close to a pure C extension without having to manually handle PyObject* or memory management.</p><h4>Steps to Create a Cython Extension:</h4><p>A typical project structure might look like this:</p><pre>sum_cython/<br>|-- sum_cython.pyx   # Cython code<br>|-- setup.py         # Script to compile<br>|-- test_sum.py      # Tests for the extension</pre><ol><li>Install Cython:</li></ol><pre>pip install cython</pre><p>2. Make sure you have a C compiler installed. (On macOS and Linux, one is usually available by default; on Windows, you can install the Microsoft C++ Build Tools.)</p><p>3. Write your extension code in a file with the .pyx extension.</p><pre># sum_cython.pyx<br># Cython Will be in charge to convert the code to C and to machine code<br><br>cpdef long suma_hasta(long n):<br>    cdef long total = 0<br>    cdef long i<br>    for i in range(n):<br>        total += i<br>    return total</pre><p><strong>What does the code do?</strong></p><ul><li><strong>cpdef</strong> allows the function to be called from both Python and C.</li><li><strong>cdef long</strong> specifies that total and i are long (C types), which boosts performance.</li><li>The loop sums numbers from 0 to n - 1.</li></ul><p>4. Create a setup.py script to compile the Cython code.</p><pre>from setuptools import setup<br>from Cython.Build import cythonize<br><br>setup(<br>    name=&quot;sum_cython&quot;,<br>    ext_modules=cythonize(&quot;sum_cython.pyx&quot;, compiler_directives={&#39;language_level&#39;: &quot;3&quot;}),<br>)</pre><p><strong>What does this </strong><strong>setup.py do?</strong></p><ul><li>Uses setuptools and cythonize to convert sum_cython.pyx to C code.</li><li>language_level=3 ensures Python 3 syntax is used.</li></ul><p>5. Compile the extension:</p><pre>python setup.py build_ext --inplace</pre><p><strong>What happens here?</strong></p><ul><li>Cython translates sum_cython.pyx to C (sum_cython.c).</li><li>The C compiler (gcc, clang, or MSVC) converts the .c file into a shared library:</li><li><strong>Linux/macOS:</strong> sum_cython.cpython-&lt;version&gt;-x86_64-linux-gnu.so</li><li><strong>Windows:</strong> sum_cython.cp&lt;version&gt;-win_amd64.pyd</li></ul><p>If everything goes well, you’ll see a .so or .pyd file, which is the compiled Cython module.</p><p>6. Import and use your newly compiled extension in Python.</p><pre># test_sum.py<br><br>import time<br>from sum_cython import suma_hasta<br><br>N = 10_000_000  # 10 million<br><br>start = time.time()<br>resultado = suma_hasta(N)<br>end = time.time()<br><br>print(f&quot;Result: {resultado}&quot;)<br>print(f&quot;Execution time: {end - start:.6f} seconds&quot;)</pre><p>Run it:</p><pre>python test_sum.py</pre><p>7. Expected Result:</p><pre>Result: 49999995000000<br>Execution time: 0.03 seconds</pre><h4>Comparison with Pure Python</h4><pre>def suma_python(n):<br>    total = 0<br>    for i in range(n):<br>        total += i<br>    return total<br><br>import time<br><br>N = 10_000_000<br>start = time.time()<br>print(suma_python(N))<br>print(f&quot;Pure Python: {time.time() - start:.6f} seconds&quot;)</pre><p>Pure Python result:</p><pre>49999995000000<br>Pure Python: 2.40 seconds</pre><h4>What Did Cython Do Internally?</h4><ul><li>Converted sum_cython.pyx into a .c file.</li><li>The .c file contains calls to pure C functions (e.g., PyLong_FromLong for creating Python integers).</li><li>The C compiler produced a shared library (.so or .pyd).</li><li>Python imports the module like any other, but the operations happen in machine code.</li></ul><h4>But What About NumPy?</h4><p>You might wonder why not just use <strong>NumPy</strong> for numeric operations. In fact, NumPy is primarily written in C and Cython under the hood, which is why it’s so fast. The same goes for many other data and math libraries in Python: they rely on these low-level C extensions to handle heavy computations efficiently.</p><h3>Conclusion</h3><p>Using C extensions, especially through <strong>Cython</strong>, is an excellent way to improve Python’s performance for CPU-intensive tasks. It can also help circumvent some of the limitations imposed by the Global Interpreter Lock (GIL), enabling more efficient parallelism in specific scenarios (though that’s a deeper topic on its own).</p><p>Now that you have a better idea of what a C extension is and how it works, you’re ready to experiment with creating your own. Give it a try and take your Python performance to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956c5de5d069" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python Works: From Hello World to Electric Signals.]]></title>
            <link>https://nicolas1009.medium.com/how-python-works-from-hello-world-to-electric-signals-a7111835f6fc?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7111835f6fc</guid>
            <category><![CDATA[interpreters]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 01:27:46 GMT</pubDate>
            <atom:updated>2025-02-13T05:40:24.063Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong><br>As I mentioned in previous articles, I used to work with colleagues who use Python on a daily basis but don’t necessarily consider themselves “developers.” Many, like me, do not hold a formal computer science degree. (For instance, my background is in Electronics, and our team also included chemists, economists, mechanical engineers, etc.)</p><p>In one of our regular discussions, we talked about PyPy — an alternative Python interpreter that uses JIT (Just-In-Time) compilation — versus the traditional CPython. My colleagues asked about how JIT works, but it’s difficult to explain without first understanding the basics of how Python itself operates. Writing this down helps me organize my thoughts and refresh my knowledge, so let’s dive in.</p><h4>1. Writing the Code</h4><p>Consider the classic example</p><pre>print(&quot;Hello World&quot;)</pre><h4>2. Lexical Analysis (Tokenization)</h4><p>First, Python’s lexer (lexical analyzer) reads the source code and converts it into a series of <strong>tokens</strong>, which are the smallest meaningful units in the language</p><pre>Tokens:<br><br>NAME: print — Identifies a function or keyword.<br>OP: ( — Opening parenthesis.<br>STRING: &quot;Hello World&quot; — String literal.<br>OP: ) — Closing parenthesis.</pre><p>Python visualization:</p><pre>import tokenize<br>from io import BytesIO<br><br>code = b&#39;print(&quot;Hello World&quot;)&#39;<br>tokens = tokenize.tokenize(BytesIO(code).readline)<br><br>for token in tokens:<br>    print(token)</pre><p>Output:</p><pre>TokenInfo(type=1 (NAME), string=&#39;print&#39;)<br>TokenInfo(type=54 (OP), string=&#39;(&#39;)<br>TokenInfo(type=3 (STRING), string=&#39;&quot;Hello World&quot;&#39;)<br>TokenInfo(type=54 (OP), string=&#39;)&#39;)</pre><h4>3. Syntax Analysis (Parsing)</h4><p>Next, the parser takes these tokens and builds an <strong>Abstract Syntax Tree (AST)</strong>, which represents the hierarchical structure of the code. It might look like this:</p><pre>&quot;&quot;&quot; AST tree &quot;&quot;&quot;<br><br>import ast<br><br>code = &#39;print(&quot;Hello World&quot;)&#39;<br>parsed_code = ast.parse(code)<br>print(ast.dump(parsed_code, indent=4))</pre><p>Output:</p><pre>Module(<br>    body=[<br>        Expr(<br>            value=Call(<br>                func=Name(id=&#39;print&#39;, ctx=Load()),<br>                args=[<br>                    Constant(value=&#39;Hello World&#39;)<br>                ],<br>                keywords=[]<br>            )<br>        )<br>    ]<br>)</pre><ul><li><strong>Module</strong>: Represents the entire file.</li><li><strong>Expr</strong>: An expression to be evaluated.</li><li><strong>Call</strong>: Indicates a function call.</li><li><strong>Name(id=’print’)</strong>: The function being called.</li><li><strong>Constant(value=’Hello World’)</strong>: The argument passed to the function.</li></ul><h4>4. Bytecode Compilation</h4><p>Once the AST is formed, Python compiles it into <strong>bytecode</strong> — a low-level, platform-independent set of instructions for the Python Virtual Machine (PVM).</p><pre>&quot;&quot;&quot;ByteCode visialization&quot;&quot;&quot;<br><br>import dis<br><br>dis.dis(&#39;print(&quot;Hello World&quot;)&#39;)</pre><pre>Output:<br><br>  1           0 LOAD_NAME                0 (print)<br>              2 LOAD_CONST               0 (&#39;Hello World&#39;)<br>              4 CALL_FUNCTION            1<br>              6 RETURN_VALUE</pre><p>For our example:</p><ol><li>LOAD_NAME 0 (print) — Loads a reference to the print function.</li><li>LOAD_CONST 0 (&#39;Hello World&#39;) — Loads the string &#39;Hello World&#39;.</li><li>CALL_FUNCTION 1 — Calls print with one argument.</li><li>RETURN_VALUE — Marks the end of execution.</li></ol><h4>5. Bytecode Execution (Python Virtual Machine)</h4><p>The <strong>Python Virtual Machine</strong> then executes this bytecode. Under the hood, these instructions translate into C function calls that interface with the operating system. In CPython, the print function calls a C function (PyFile_WriteObject()), which in turn makes operating system calls (e.g., write() on Linux or WriteConsole() on Windows) to display text on the console.</p><h4>6. Operating System Calls</h4><p>After the Python layer, we move into <strong>OS-level</strong> calls. These calls communicate with the kernel, which handles interactions with hardware. In Linux, for instance, the write() call might look like the following in x86-64 assembly (this depends on CPU architecture):</p><pre>mov rax, 1      ; system call number for write<br>mov rdi, 1      ; file descriptor 1 (stdout)<br>mov rsi, msg    ; address of the string &quot;Hello World\n&quot;<br>mov rdx, 12     ; length of the string in bytes<br>syscall         ; hand over control to the kernel</pre><ul><li><strong>rax = 1</strong>: Syscall number (1 for write).</li><li><strong>rdi = 1</strong>: File descriptor for standard output (stdout).</li><li><strong>rsi = msg</strong>: Memory address of the string.</li><li><strong>rdx = 12</strong>: Number of bytes to write.</li><li><strong>syscall</strong>: Executes the system call.</li></ul><h4>7. Machine Code</h4><p>The assembly instructions themselves are then translated into <strong>machine code</strong> (binary). At this level, everything is just a sequence of 0s and 1s understood by the CPU.</p><pre>Example CPU x86-64<br><br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+<br>| Assembly instruction    | Machine code(Hexadecimal)            | Binary(0s and1s)                                                                  |<br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+<br>| mov rax, 1              | 48 C7 C0 01 00 00 00                 | 01001000 11000111 11000000 00000001 00000000 00000000 00000000                    |<br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+<br>| mov rdi, 1              | 48 C7 C7 01 00 00 00                 | 01001000 11000111 11000111 00000001 00000000 00000000 00000000                    |<br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+<br>| mov rsi, &lt;addr&gt;         | 48 BE &lt;addr&gt;                         | 01001000 10111110 &lt;Binary Address&gt;                                                |<br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+<br>| mov rdx, 12             | 48 C7 C2 0C 00 00 00                 | 01001000 11000111 11000010 00001100 00000000 00000000 00000000                    |<br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+<br>| syscall                 | 0F 05                                | 00001111 00000101                                                                 | <br>+-------------------------+--------------------------------------+------------------------------------------------------------------------------------+</pre><h4>8. Electric Signals</h4><p>Finally, these binary instructions correspond to <strong>electric signals</strong> traveling through the CPU’s transistors and logic gates. A “0” might be interpreted as 0 volts and a “1” as 5 volts (depending on the hardware). The CPU fetches, decodes, and executes these signals, ultimately causing the text <strong>Hello World</strong> to appear on your screen.</p><p>A CPU is the union of multiple Logic gates, and a logic gate is millions of transistors embedded.</p><p>Of course how works a CPU is more complex than this, but at high level I think is ok this brief explanation.</p><h3>Conclusion</h3><p>When you run a Python program — whether it’s a simple print(&quot;Hello World&quot;) or a complex application—all these steps happen behind the scenes:</p><ol><li><strong>Source Code</strong></li><li><strong>Lexical Analysis (Tokens)</strong></li><li><strong>Syntax Analysis (AST)</strong></li><li><strong>Bytecode Compilation</strong></li><li><strong>Bytecode Execution (PVM)</strong></li><li><strong>Operating System Calls</strong></li><li><strong>Assembly Instructions</strong></li><li><strong>Machine Code</strong></li><li><strong>Electric Signals (CPU-Level)</strong></li></ol><p>Although this example is straightforward, more complex code follows the same basic process — just with more intricate ASTs, bytecode, assembly, and system interactions. Modern computers handle all of this extremely quickly, hiding most of the complexity from us. It’s truly fascinating how seamlessly it all comes together.</p><p>We haven’t delved too deeply into topics like advanced bytecode structures, assembly intricacies, or JIT compilation, but this overview should be a good starting point for anyone curious about what happens under the hood when you run Python code. It’s amazing how much work goes on just to print a single line of text!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7111835f6fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Part 4, Elasticsearch Configuration Essentials for Minikube.”]]></title>
            <link>https://nicolas1009.medium.com/part-4-elasticsearch-configuration-essentials-for-minikube-970ad738d0b6?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/970ad738d0b6</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 23:50:15 GMT</pubDate>
            <atom:updated>2023-11-06T23:50:15.269Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to <strong>Part 4</strong> of our search engine project series. In this segment, we’ll focus on deploying Elasticsearch within our Minikube cluster, which we established in <a href="https://medium.com/@nicolas1009/integrating-redis-with-backend-in-minikube-a-step-by-step-guide-part-3-806f00851606"><strong><em>Part 3</em></strong></a>. This article is designed to be concise, guiding you through the necessary steps to get your Elasticsearch database up and running.</p><p>(Full repo in this <a href="https://github.com/Click0910/search_engine_backend"><strong><em>link</em></strong></a><strong><em>.)</em></strong></p><p>Initially, the Elasticsearch instance will not contain any data. Populating the database requires configuration of our web crawler to begin indexing. We will delve into this process in detail in our upcoming article, which will be dedicated to data ingestion and setting up the crawler for Elasticsearch.</p><p>By the end of this tutorial, you’ll have a fully functional Elasticsearch service ready on your local Kubernetes cluster, setting the stage for the next phase of our project: Data Acquisition and Management.</p><p><strong>following the next diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*OOe-Hrlv9ezkNuxoQIRz5Q.png" /></figure><p><strong>Understanding Our Backend Query Process</strong></p><p>When a user initiates a query, our backend system engages in a two-tiered retrieval process:</p><p>1. Cache Check: The query is first checked against our Redis cache. If a cached answer exists (indicating a previous user has asked the same question), this response is immediately returned to the user, ensuring a swift delivery of information.</p><p>2. Elasticsearch Fallback: In the absence of a cached answer in Redis, the backend then defers to Elasticsearch. Here, it conducts a thorough search and retrieves the relevant information.</p><p>3. Caching and Response: Once the answer is obtained from Elasticsearch, it is not only sent back to the user but also stored in Redis. This step is crucial as it updates the cache with the new information, optimizing future response times for the same query.</p><p>By utilizing this strategy, we ensure efficiency and speed in our response mechanism, leveraging Redis for quick access and Elasticsearch for comprehensive data retrieval.</p><h3>Setting Up Elasticsearch on Minikube</h3><p>Following our previous work on Redis, it’s time to integrate Elasticsearch into our Minikube environment. This article guides you through creating the necessary configuration files and deploying Elasticsearch.</p><p><strong>Prerequisites:</strong></p><p>Before proceeding, ensure that you have completed the setup from Part 3, which includes the Minikube cluster configuration.</p><p><strong><em>Step 1: Configure Elasticsearch Deployment</em></strong></p><p>Craft an Elasticsearch deployment file named elastic-search-deploy.yaml.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: elasticsearch<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: elasticsearch<br>  template:<br>    metadata:<br>      labels:<br>        app: elasticsearch<br>    spec:<br>      containers:<br>      - name: elasticsearch<br>        image: docker.elastic.co/elasticsearch/elasticsearch:7.10.0<br>        env:<br>        - name: discovery.type<br>          value: single-node<br>        ports:<br>        - containerPort: 9200<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: elasticsearch-service<br>spec:<br>  type: NodePort<br>  ports:<br>    - port: 9200<br>      targetPort: 9200<br>      nodePort: 30200  # Elige un puerto que esté libre en tu máquina<br>  selector:<br>    app: elasticsearch</pre><p><strong><em>Step 2: Apply the Deployment</em></strong></p><p>Deploy your Elasticsearch service to Minikube using Kubernetes’ command-line tool:</p><pre>kubectl apply -f elastic-search-deploy.yaml</pre><p><strong><em>Step 3: Create the Elasticsearch Client</em></strong></p><p>Establish an Elasticsearch client within your backend. You’ll need to create and configure the appropriate file:</p><pre>from elasticsearch_async import AsyncElasticsearch<br>from app.app import app<br><br><br>async def get_elasticsearch() -&gt; AsyncElasticsearch:<br>    es_client = AsyncElasticsearch(<br>        hosts=[{&quot;host&quot;: &quot;your-elasticsearch-host&quot;, &quot;port&quot;: 9200}],<br>    )<br>    try:<br>        # Verificar la conexión<br>        if not await es_client.ping():<br>            raise ValueError(&quot;Conexión fallida&quot;)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        raise e<br>    return es_client<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    # Inicializar la conexión a Elasticsearch en el inicio de la aplicación<br>    app.state.elasticsearch = await get_elasticsearch()<br><br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown_event():<br>    await app.state.elasticsearch.close()</pre><p>In this code we create a connection pool for asynchrony connections.</p><p><strong>Note on Security:</strong></p><p>You might notice that we haven’t set up security credentials. While Elasticsearch provides security features within the Elastic Stack, these typically require a paid license. However, there are limited free options available.</p><p><strong>If you wish to enable security features and credentials, follow these steps:</strong></p><p><strong><em>Deploying Elasticsearch Without Initial Credentials</em></strong></p><p>To deploy Elasticsearch without setting up credentials initially, you’ll use the .yaml file created previously.</p><p><strong><em>Step 1: Execute Elasticsearch Password Setup</em></strong></p><p>After deploying Elasticsearch, set up autogenerated passwords by running:</p><pre>kubectl exec -it &lt;elastic-search-pod-name&gt; - bin/elasticsearch-setup-passwords auto</pre><p>Replace &lt;elastic-search-pod-name&gt; with the actual name of your Elasticsearch pod.</p><p>This command will generate random credentials, which will appear in your command line output.</p><p>Important:</p><p>Record these credentials immediately — they are essential for accessing your Elasticsearch instance.</p><p>Store them in a secure location.</p><p><strong><em>Step 2: Update the Backend Elasticsearch Client</em></strong></p><p>Incorporate the generated credentials into your backend’s Elasticsearch client configuration.</p><pre>async def get_elasticsearch() -&gt; AsyncElasticsearch:<br>    es_client = AsyncElasticsearch(<br>        hosts=[{&quot;host&quot;: &quot;your-elasticsearch-host&quot;, &quot;port&quot;: 9200}],<br>        http_auth=(&#39;elastic&#39;, &#39;tQPMJXadBe&#39;),<br>    )<br>    return es_client</pre><p><strong><em>Step 3: Create Kubernetes Secrets</em></strong></p><p>Use the credentials to create a Kubernetes secret. This will securely store the credentials within your cluster.</p><pre>kubectl create secret generic elasticsearch-secret --from-literal=username=elastic-username --from-literal=password=elastic-password</pre><p>Fill in &lt;secret-name&gt;, &lt;elastic-username&gt;, and &lt;elastic-password&gt; with the appropriate values.</p><p><strong><em>Step 4: Create a ConfigMap to Enable Security</em></strong></p><p>Construct a ConfigMap that includes the necessary parameters to enable security features in Elasticsearch.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: elasticsearch-config<br>data:<br>  elasticsearch.yml: |<br>    xpack.security.enabled: true<br>    # Adjustments for the Elasticsearch heap (e.g., 1g, 2g, etc.)<br>    # Specifying the percentage of the HEAP here is an example and may not be recommended for your specific case.<br>      ES_JAVA_OPTS: &quot;-Xms512m -Xmx512m&quot;<br>    # Configurations for node discovery in a Kubernetes environment<br>      discovery.type: single-node<br>    # other necessary configurations for Elasticsearch...</pre><p>Note that this configuration will depend of the elastic search version that we are deploying.</p><p><strong><em>Step 5: Modify the Deployment File</em></strong></p><p>Adjust your existing elastic-search-deploy.yaml file to make use of the secret and ConfigMap for enabling security.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: elasticsearch-deployment<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: elasticsearch<br>  template:<br>    metadata:<br>      labels:<br>        app: elasticsearch<br>    spec:<br>      containers:<br>      - name: elasticsearch<br>        image: docker.elastic.co/elasticsearch/elasticsearch:7.10.0<br>        env:<br>          - name: ELASTIC_PASSWORD<br>            valueFrom:<br>              secretKeyRef:<br>                name: elasticsearch-secret<br>                key: password<br>          - name: ELASTIC_USERNAME<br>            valueFrom:<br>              secretKeyRef:<br>                name: elasticsearch-secret<br>                key: username<br>        ports:<br>        - containerPort: 9200<br>        volumeMounts:<br>        - name: elasticsearch-config<br>          mountPath: /usr/share/elasticsearch/config/elasticsearch.yml<br>          subPath: elasticsearch.yml<br>      volumes:<br>      - name: elasticsearch-config<br>        configMap:<br>          name: elasticsearch-config</pre><p><strong><em>Future Production Enhancements</em></strong></p><p>For a production environment, we will introduce readiness and liveness probes to ensure smooth traffic management and self-healing capabilities. Additionally, we’ll configure resource limits to optimize performance and costs. Implementing volume mounts for persistent storage will also be crucial to prevent data loss during pod restarts, among other enhancements.</p><p>However, our current setup suffices for the initial deployment stage.</p><p>By completing these steps, you’ll have a functioning Elasticsearch instance within your local development environment. In our next installment, we’ll explore how to securely manage access and protect your data within Elasticsearch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970ad738d0b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Integrating Redis with Backend in Minikube: A Step-by-Step Guide. Part 3”]]></title>
            <link>https://nicolas1009.medium.com/integrating-redis-with-backend-in-minikube-a-step-by-step-guide-part-3-806f00851606?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/806f00851606</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 14:24:19 GMT</pubDate>
            <atom:updated>2023-10-20T14:44:28.621Z</atom:updated>
            <content:encoded><![CDATA[<p>The full repo is in this <a href="https://github.com/Click0910/search_engine_backend/tree/main"><strong><em>GitHub_Link</em></strong></a></p><p>In previous parts (<a href="https://medium.com/@nicolas1009/building-blocks-of-a-search-engine-a-dive-into-backend-services-642ccdc5829b">part 1</a>, <a href="https://nicolas1009.medium.com/search-engine-backend-services-a-python-implementation-part-2-backend-986e8f6227c4">part 2</a>) we started the implementation of a search engine.</p><p>In this <strong>Part 3</strong>, we will integrate Redis into our search engine. The primary goal of integrating Redis is to enhance performance and reduce strain on our database (in our case, Elasticsearch. Details on deployment and integration with Elasticsearch will be covered in the next article).</p><p>From an architectural perspective, Redis will be queried right after the user’s query is normalized. If the data exists in Redis, it is returned to the user. If not, the query is executed in the database, the result is stored in Redis, and then returned to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*_-dQfC8glLV0foGsCSq4Kw.png" /></figure><h3>Prerequisites:</h3><p>In this project, we will deploy Redis on a Kubernetes cluster. For development and testing, I’ll be using<strong> Minikube</strong>, but feel free to use whichever environment you prefer. Once everything is set up, we’ll transition to an <strong>EKS cluster</strong> in <strong>AWS</strong>. However, for now, Minikube will suffice.</p><p>The first step is to install Minikube. You can do so by following this <a href="https://minikube.sigs.k8s.io/docs/start/"><strong><em>link</em></strong></a></p><p>Separately, you’ll also need to install the kubectl client if you haven’t done so. <a href="https://k8s-docs.netlify.app/en/docs/tasks/tools/install-kubectl/#:~:text=Install%20kubectl%20binary%20with%20curl%20on%20Windows%201,is%20the%20same%20as%20downloaded%3A%20kubectl%20version%20--client"><strong><em>link</em></strong></a></p><p>Start minikube:</p><pre>minikube start</pre><p>Create the next .yaml files and apply them:</p><p><strong><em>redis-deploy.yaml</em></strong></p><p>For now, we’ll employ a basic Redis configuration as our primary focus is on development. Later, we will dive into resource configurations, persistent storage, readiness probes, liveness probes, restore policies, and more.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: redis<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: redis<br>  template:<br>    metadata:<br>      labels:<br>        app: redis<br>    spec:<br>      containers:<br>      - name: redis<br>        image: redis:latest<br>        ports:<br>        - containerPort: 6379<br>        volumeMounts:<br>        - name: config<br>          mountPath: /usr/local/etc/redis/redis.conf<br>          subPath: redis.conf<br>        args:<br>        - redis-server<br>        - /usr/local/etc/redis/redis.conf<br>      volumes:<br>      - name: config<br>        configMap:<br>          name: redis-config<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: redis-service<br>spec:<br>  type: NodePort<br>  ports:<br>    - port: 6379<br>      targetPort: 6379<br>      nodePort: 30379  # Choose a port that is free in your machine<br>  selector:<br>    app: redis</pre><p><strong><em>redis-conf-map.yaml</em></strong></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: redis-config<br>data:<br>  redis.conf: |<br>    requirepass mypassword</pre><pre>kubectl apply -f redis-deploy.yaml<br>kubectl apply -f redis-conf-map.yaml</pre><p><strong>Note</strong>: The <strong><em>redis-deploy.yaml</em></strong> file deploys a single replica of Redis and exposes a NodePort for communication outside the cluster (in this case, Minikube). This setup is used because our backend isn’t currently deployed within the same cluster. In the future, we plan to deploy our backend within the cluster. However, during this development stage, we often need to make changes, adjust logic, add error handling, implement unit tests, etc. For practicality at this initial stage, I prefer to keep the backend outside the cluster. Nevertheless, if you wish, you can deploy it inside the cluster now. It’s important to note that in production — once everything is finalized and we transition to an EKS — the NodePort will be substituted by a load balancer. This shift will occur in a later stage; for now, the NodePort serves our needs well.</p><p><strong>Note 2</strong>: The purpose of the redis-conf-map.yaml file is to set up a Redis password. One of the most common ways to achieve this is through config maps.</p><p><strong>Note 3</strong>: In the redis-conf-map.yaml file, you might observe that the Redis password is hardcoded. While this approach is acceptable for development and testing phases, it’s inadvisable for production, particularly due to security concerns. In a production environment, this password, along with other credentials, will be stored as Kubernetes secrets. For now, just focus in development and implementation.</p><p>The subsequent step is to ensure everything is operating within Minikube and to retrieve the Minikube IP. Execute the following commands:</p><pre>kubectl get pods<br>kubectl get svc<br>minikube ip</pre><p><strong>Note 4</strong>: Typically, the Minikube IP address is 192.168.99.100, but it’s prudent to confirm. This IP is pivotal as it needs to be integrated into the Redis client within our backend. Another crucial parameter is the NodePort, which we’ve designated as 30379(you can check it in <strong><em>redis-deploy.yaml</em></strong>).</p><p><strong>Hint</strong>: If you encounter any issues during deployment, inspect the pod logs. If you’re familiar with Kubernetes and the Lens IDE, consider using it. It provides a graphical interface that is quite user-friendly.</p><p>With Redis now deployed, the next step is to integrate it with our backend. To accomplish this, we’ll:</p><p>1. Create a Redis client to establish a connection.</p><p>2. Modify the search function.</p><p>3. For better organization and maintainability, we’ll set up a utils/redis module to keep our code granular.</p><p>Let’s begin.</p><p><strong><em>Redis Client:</em></strong></p><p><strong><em>db_utils/redis_client.py</em></strong></p><pre>import aioredis<br>from app import app<br><br>redis_pool = None<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    global redis_pool<br>    redis_pool = await aioredis.create_redis_pool(<br>        address=(&#39;192.168.99.100&#39;, 30379),<br>        db=0,<br>        password=&#39;mypassword&#39;<br>    )<br><br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown_event():<br>    redis_pool.close()<br>    await redis_pool.wait_closed()<br><br><br>async def get_value(key: str):<br>    async with redis_pool as conn:<br>        value = await conn.get(key, encoding=&#39;utf-8&#39;)  # Encoding argument<br>    return value</pre><p>In this script, we utilize aioredis to establish an asynchronous connection with Redis. We’ve implemented “startup” and “shutdown” events to initiate and terminate the connection pool, respectively. Additionally, we deserialize Redis responses from bytes to strings using encoding=’utf-8&#39;.</p><p>Much like with Minikube, hardcoding passwords, ports, hosts, etc. in the code is acceptable for development and testing purposes. However, this approach is not suitable for production. In a production environment, such credentials should be stored in environment variables, secret vaults, and the like. Ideally, these would be organized in a config.py file. But since our current emphasis is on development, we&#39;ll address and optimize these configurations for production at a later stage. For the time being, this setup will be enough.</p><p><strong><em>The next task is to develop the utility for Redis</em></strong>:</p><p><strong><em>Utils/redis_utils.py</em></strong></p><pre>from app.db_utils.redis_client import redis_pool<br>import json<br><br><br>async def search_in_redis(normalized_query):<br>    async with redis_pool as redis_client:<br>        cache_result = await redis_client.get(normalized_query, encoding=&#39;utf-8&#39;)<br>        if cache_result:<br>            # If result is in cache, deserialize it and return it.<br>            return json.loads(cache_result)<br><br><br>async def store_in_redis(normalized_query, result):<br>    async with redis_pool as redis_client:<br>        await redis_client.set(normalized_query, json.dumps(result))</pre><p>This module houses functions that manage the connection pool, such as search_in_redis and store_in_redis. Organizing our code this way ensures it remains granular and easily maintainable. However, if you have an alternate approach or design for structuring the code, you’re encouraged to implement it</p><p><strong><em>Now, it’s time to adjust our search function, but the modifications are straightforward:</em></strong></p><p><strong><em>services/search_service.py</em></strong></p><pre>from typing import List<br>from app.models.search_models import SearchQuery, SearchResult<br>from app.utils.query_process import BaseProcessQuery<br>from app.db_utils.translate_query import translate_to_dsl<br>from app.utils.redis_utils import search_in_redis, store_in_redis<br><br><br>process = BaseProcessQuery()<br><br><br>async def search(query: SearchQuery) -&gt; List[SearchResult]:<br>    # Normalized a proces de query<br>    # In future could be possible to make more query process.<br>    normalized_query, _, _ = process.process(query.query)<br>    # Check in redis cache<br>    cache_result = await search_in_redis(normalized_query)<br><br>    if cache_result:<br>        # Transform the dictionaries to the SearchResult Schema.<br>        return [SearchResult(**result_dict) for result_dict in cache_result]<br><br>    query_translated = translate_to_dsl(query)<br>    # db_search() will be the function that consult the DB. Elastic cache is not implemented yet.<br>    # results = await db_search(query_translated)<br>    results = [SearchResult(title=&quot;Example Result&quot;, url=&quot;https://example.com&quot;, snippet=&quot;This is an example result.&quot;)]<br><br>    # Store the result in Redis for further consults.<br>    await store_in_redis(normalized_query, results)<br><br>    return results</pre><p>As you can observe, the changes are minimal. We’ve merely incorporated the redis_utils imports, and beyond that, not much has changed.</p><p>With that, our backend integration with Redis is complete.</p><h3>Conclusion:</h3><p>In this article, we accomplished the following:</p><p>1. Deployed Redis in Minikube.</p><p>2. Integrated Redis with our backend through an asynchronous pool connection.</p><p>3. Made essential code adjustments to our backend.</p><p>In the upcoming article, Part 4, we will delve into the deployment and integration of Elastic Search.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806f00851606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Search Engine Backend Services: A Python Implementation — Part 2: Backend”]]></title>
            <link>https://nicolas1009.medium.com/search-engine-backend-services-a-python-implementation-part-2-backend-986e8f6227c4?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/986e8f6227c4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 16:16:36 GMT</pubDate>
            <atom:updated>2023-10-13T16:35:42.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Search Engine Backend Services: A Python Implementation — Part 2: Backend”</h3><p>You can find the code repo <a href="https://github.com/Click0910/search_engine_backend/tree/main"><strong><em>here.</em></strong></a></p><p>In <a href="https://nicolas1009.medium.com/building-blocks-of-a-search-engine-a-dive-into-backend-services-642ccdc5829b"><strong><em>part 1</em></strong></a>, we explored the high-level architecture and components of a search engine</p><p>In this Part 2, we are going to implement the backend using python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*WKs2mmaqIBu0vLdagIOHoA.png" /></figure><p>We can consider the backend as the controller of our search engine. This controller will also be in charge of instructing the crawler when to surf the web. Some people might view this controller as a kind of orchestrator (which essentially it is) and believe it shouldn’t execute any logic. As seen in the diagram, there are two components that execute business logic.</p><p>For a cleaner model and architecture, these components ideally would reside in another micro-service (for example, a Query Process Microservice). However, in a micro-service architecture, adding more microservices implies adding more complexity to the communication — more calls, more requests, which equals more latency. Increased latency can affect performance, and in a search engine, we strive for optimal performance. For this reason, the Query Process and Query Translator, at least in this standard implementation, are going to “live” in the backend controller.</p><p>It’s possible to mitigate latency issues by using a protocol like gRPC for microservices communication (given that gRPC is faster than HTTP), however, not all web frameworks integrate well with this protocol. So, for now, we’ll maintain the current setup</p><p>So lets go:</p><p><strong>Note:</strong></p><p>· This is a standard implementation that can be adapted to a specific business case. We are going to use Python and FastAPI.</p><p>· Interaction with Elasticsearch and Redis will be explored in further articles.</p><p><strong><em>This is the backend server initialization:</em></strong></p><pre>#app.py<br><br>from fastapi import FastAPI<br>from app.api import search<br><br>app = FastAPI()<br><br>app.include_router(search.router)</pre><p><strong><em>This is the endpoint implementation that will be receive the user query:</em></strong></p><pre>#api/search.py<br><br>from fastapi import APIRouter, HTTPException, Status<br>from app.models.search_models import SearchQuery, SearchResult<br>from app.services.search_service import search<br><br>router = APIRouter()<br><br><br>@router.post(&quot;/search/&quot;, response_model=list[SearchResult])<br>async def search_endpoint(query: SearchQuery):<br>    results = search(query.query)<br>    if not results:<br>        raise HTTPException(status_code=Status.HTTP_404_NOT_FOUND, detail=&quot;No results found&quot;)<br>    return results</pre><p><strong><em>This is the model schema:</em></strong></p><pre>#models/search_models.py<br><br>from pydantic import BaseModel<br><br><br>class SearchQuery(BaseModel):<br>    query: str<br><br><br>class SearchResult(BaseModel):<br>    title: str<br>    url: str<br>    snippet: str</pre><p><strong><em>This is the class that process the query:</em></strong></p><pre>#utils/query_process.py<br><br>import re<br>import spacy<br>from spellchecker import SpellChecker<br>import nltk<br><br><br>nltk.download(&#39;punkt&#39;)<br>spacy.cli.download(&quot;en_core_web_sm&quot;)<br><br><br>class BaseProcessQuery:<br>    def __init__(self):<br>        self.spell_checker = SpellChecker()<br>        self.nlp = spacy.load(&#39;en_core_web_sm&#39;)<br><br><br>    def normalize(self, query):<br>        query = query.lower()<br>        query = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, query)<br>        return query<br><br>    def breakdown_query(self, query):<br>        terms = nltk.word_tokenize(query)<br>        return terms<br><br>    def identify_entities_and_concepts(self, terms):<br>        doc = self.nlp(&quot; &quot;.join(terms))<br>        entities = [ent.text for ent in doc.ents]<br>        concepts = [token.lemma_ for token in doc if not token.is_stop]<br>        return entities, concepts<br><br>    def disambiguate_and_correct(self, terms):<br>        corrected_terms = [self.spell_checker.correction(term) for term in terms]<br>        return corrected_terms<br><br>    def query_expansion(self, terms):<br>        expanded_query = &quot; &quot;.join(terms)<br>        return expanded_query<br><br>    def reconstruct_query(self, terms):<br>        reconstructed_query = &quot; &quot;.join(terms)<br>        return reconstructed_query<br><br>    def process(self, query):<br>        normalized_query = self.normalize(query)<br>        terms = self.breakdown_query(normalized_query)<br>        entities, concepts = self.identify_entities_and_concepts(terms)<br>        corrected_terms = self.disambiguate_and_correct(terms)<br>        expanded_query = self.query_expansion(corrected_terms)<br>        reconstructed_query = self.reconstruct_query(expanded_query)<br>        return reconstructed_query, entities, concepts</pre><p><strong><em>Here is a function that translates the normalized query to DSL (for Elasticsearch). For a cleaner OOP approach, feel free to implement this functionality within a class:</em></strong></p><pre>utils_db/translate_query.py<br><br>from elasticsearch_dsl import Search, Q<br><br><br>def translate_to_dsl(query: str):<br>    # This is a simple translation. In practice you will need to make a more sophisticated translation.<br>    dsl_query = Q(&quot;multi_match&quot;, query=query, fields=[&#39;title&#39;, &#39;content&#39;, &#39;description&#39;])<br>    return dsl_query<br><br># The DSL query will be used to consult elastic search DB.</pre><p><strong><em>Here’s the function that executes the query search. If you prefer a cleaner OOP approach, feel free to encapsulate this functionality within a class:</em></strong></p><pre>from typing import List<br>from app.models.search_models import SearchQuery, SearchResult<br>from app.utils.query_process import BaseProcessQuery<br>from app.db_utils.translate_query import translate_to_dsl<br><br>&#39;&#39;&#39;<br>This is a standard implementation.<br><br>Integration with elastic search will be explored later in another article.<br>&#39;&#39;&#39;<br><br>process = BaseProcessQuery()<br><br><br># Function tha execute the search of a query<br>def search(query: SearchQuery) -&gt; List[SearchResult]:<br>    query_translated = translate_to_dsl(query)<br>    # Use the Methods from BaseProcessQuery that are necessary etc.<br>    # Mock search service<br>    return [SearchResult(title=&quot;Example Result&quot;, url=&quot;https://example.com&quot;, snippet=&quot;This is an example result.&quot;)]</pre><p>And there you have it — the foundational structure of our backend. In upcoming articles, we will delve into more complex aspects, integrating Elasticsearch, web crawlers, Redis, and addressing error handling to enhance the robustness of this structure. For now, this serves as a solid first step in our journey. Looking forward to exploring more intricacies together in subsequent parts. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=986e8f6227c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Building Blocks of a Search Engine: A Dive into Backend Services. Part 1”]]></title>
            <link>https://nicolas1009.medium.com/building-blocks-of-a-search-engine-a-dive-into-backend-services-642ccdc5829b?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/642ccdc5829b</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 23:51:10 GMT</pubDate>
            <atom:updated>2023-10-20T14:05:18.224Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an article series about search engines.</p><p>This <strong>Part 1</strong> will be an introduction article. The next parts will be more practical. Part 2 will cover Backend implementation in <strong>Python.</strong></p><p>In this first article, I want to talk about search engines and propose an initial and standard architecture on how to design and implement one.</p><h3><strong>What is a search engine?</strong></h3><p>A search engine is a complex software tasked with responding to a query made by a user, like Google or Bing, for example. The user makes a query, and Google searches for answers to send to the user, in this case, web links. But search engines are not only for the web; a private company can have one, for instance, to search for internal resources, like private wiki documentation or something similar. The general idea of a search engine can be applied to different fields and not just to the web. All of us have used Google, so we can intuitively understand what constitutes a search engine, but how does it work exactly?</p><p>As mentioned before, a search engine is a complex software composed of multiple parts or, more precisely, multiple pieces of software. In a real project, a large software is the union of different “mini softwares” that work together to form that large software, like Lego; you use small Lego blocks to create a complex Lego structure.</p><p>So which Lego blocks conform our search engine?</p><p><strong><em>Search Engine Lego blocks:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*hx-0rdvhA0EhXdEMuDBQMA.png" /></figure><p>In the previous image we can see the components that composed our search engine.</p><h3><strong><em>Web crawler:</em></strong></h3><p>A web crawler, often referred to as a spider bot, traverses the web much like a surfer. While surfing, it visits websites and collects certain data (such as metadata, HTML, hyperlinks) from the visited websites.</p><p>Then, this data is sent to the next Lego block, which is the index service. Whether the data of a website is sent individually and instantly when the website is visited, or sent as a block of website data, depends on how we design the crawler and the technical requirements. This technical decision will be explored in a further article where we will delve deeper into crawlers and implement some using Python.</p><h3><strong><em>Index service:</em></strong></h3><p>This Lego block receives the data sent from the crawler, indexes it, and gives it a proper structure. The main purpose of this service is to provide a proper structure to the data before sending it to the database because, as you can see in the diagram and as you might imagine, the information displayed by our search engine needs to be stored in a database.</p><p>The data needs to be indexed and structured in a special data structure, and the favorite data structure for indexing our data is something called an “inverted index”. Another possible data structure could be a binary tree. The main disadvantage of using a binary tree is that the tree can become unbalanced, and we don’t want that. Further article going deeper will be available soon.</p><p>Our data that collect the crawler now is indexing and structured, now is time to store into a proper DB.</p><h3>Data Base:</h3><p>At a high level, this Lego block is the easiest to understand; it’s just a database where the index stores the structured data. However, this database needs to be special. It must be highly optimized, high-performance, and flexible, because the structure and the schema of the data usually are dynamic, and we want our database to be flexible and not cause us problems. So, ideally, the database should be of a NoSQL type.</p><p>One of the most popular databases for search engines is Elasticsearch, which is also my favorite. In a future article, we can delve deeper into this database and discuss how to implement it.</p><p>We can essentially say that this is the backbone of our search engine. The aforementioned process outlines how data is collected and stored. But what happens when a user makes a query? How does this work? To understand better, follow the next diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Uidsnda1_IoD5MsL7gU7-Q.png" /></figure><p><strong><em>The pipeline is as follows:</em></strong></p><p>· The user makes a query.</p><p>· The query is sent to a backend (which we can call the search engine controller).</p><p>· The backend receives the query and processes it (normalizes the query).</p><p>· With the normalized query, the backend consults the caching server (like Redis) to check if the answer to the query is stored, for example in Redis. If it is stored in Redis, the info is returned to the user.</p><p>· If it’s not in Redis, the normalized query needs to be translated to a NoSQL query to consult the DB (in Elasticsearch, something called DSL queries is used).</p><p>· With the user query translated to a DSL query, the backend consults the DB (Elasticsearch).</p><p>· The info is stored in Redis and finally sent back to the user.</p><p>In this minimalistic architecture, I decided to handle the query processing and query translation within the backend (search engine controller). However, this is a technical decision that can vary, and it has its pros and cons. Also, it’s important to mention that the backend can control and establish when the crawler will surf the web. This will be explored in further articles.</p><p><strong><em>Next is the full picture of the architecture:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Q2_F5N152tcqaA3Z6fAgAw.png" /></figure><p>In Part 2, we will delve deeper into the backend service, exploring why I decided to include the query processing and query translation within the backend, along with a standard implementation using Python.</p><p>The upcoming articles will be more technical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642ccdc5829b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Understanding Polymorphism and Interfaces in Python: A Deep Dive into Duck Typing and Abstract…]]></title>
            <link>https://nicolas1009.medium.com/understanding-polymorphism-and-interfaces-in-python-a-deep-dive-into-duck-typing-and-abstract-1da1dba4e507?source=rss-477d76d46418------2</link>
            <guid isPermaLink="false">https://medium.com/p/1da1dba4e507</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[abstract-class]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[Nicolas Bernal]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 14:58:47 GMT</pubDate>
            <atom:updated>2023-10-02T17:26:13.693Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Understanding Polymorphism and Interfaces in Python: A Deep Dive into Duck Typing and Abstract Classes”</h3><p>If you don’t have a bachelor’s degree in computer science and embarked on your software development journey with Python as your initial language, learning in a self-taught manner through reading, watching tutorials, and so forth, then you’re much like me.</p><p>My bachelor’s degree is in Electronic Engineering. While I did attend programming courses in the initial terms, I must confess I didn’t pay them much heed.</p><p>If your journey mirrors mine, and Python was your starting point in software, then it’s likely you haven’t come across the terms “polymorphism” and “interfaces” often. However, when you transition to other languages like Java or C# for professional reasons, you’ll realize just how crucial these concepts are, especially in the realm of Object-Oriented Programming (OOP).</p><p>Python, being a versatile language that supports OOP, should ideally introduce these concepts, right? So, why don’t we hear about them as much in Python? The reason is simple: while these concepts do exist in Python, they are implicit rather than explicit. You might be using them without even realizing it. It’s akin to breathing — nobody taught you as a baby; it was innate. Let’s dive a bit deeper.</p><p>To start, let’s define polymorphism and interfaces. Both can seem complex initially but are more straightforward than they appear.</p><p><strong>Polymorphism:</strong></p><p>In OOP, polymorphism refers to the ability to treat objects from different classes as though they belong to a single class, provided they share a common set of operations or methods.</p><p>What the hell was that? Don’t worry is not that bad. Think of it this way: in real life, objects can serve multiple functions. Fire, for example, can be used for cooking or as a heat source on chilly nights. Here, one object (fire) has multiple uses depending on the context. Similarly, in OOP, an object can perform varying actions based on its context. Remember, polymorphism is an abstract OOP concept. To utilize it practically, we often rely on interfaces.</p><p><strong>Interfaces:</strong></p><p>As hinted earlier, interfaces are the tangible tools enabling polymorphism. In OOP, an interface acts as a contract that mandates which methods a class must implement if it uses that interface. Essentially, the interface tells classes, “Want to use me? Ensure you include these methods.” It’s worth to mention that interfaces are explicit tools used to achieve polymorphism. In languages like <strong>Java or C#</strong>, they are defined distinctly.</p><pre>interface flyer{<br>    void fly();<br>}</pre><p>Now, Consider the following analogy to grasp polymorphism and interfaces better:</p><p>Imagine we have an universal remote control compatible with various devices: a TV, DVD player, and sound system. Each device functions differently and is based on distinct technologies. Yet, a single remote can turn any of them on or off. In this instance, the remote doesn’t concern itself with the inner workings of the devices. It only recognizes the “on” and “off” commands.</p><p><strong>In programming words:</strong></p><p>1. Each device (TV, DVD, Sound System) represents a class.</p><p>2. The remote doesn’t directly interact with these devices. It communicates through an interface that establishes methods like <strong>switch_on() or switch_off().</strong></p><p>3. Every device has its unique <strong>switch_on() and switch_off()</strong> method.</p><p>4. Owing to polymorphism, one remote can control various devices, negating the need for a separate remote for each device.</p><p>This would be the pseudo code:</p><pre>interface ElectronicDevice {<br>    method turnOn()<br>    method turnOff()<br>}<br><br>class Television implements ElectronicDevice {<br>    method turnOn() {<br>        // logic to turn the TV on<br>    }<br>    method turnOff() {<br>        // logic to turn the TV off<br>    }<br>}<br><br>class DVDFebrplayer implements ElectronicDevice {<br>    method turnOn() {<br>        // logic to turn the DVD player on<br>    }<br>    method turnOff() {<br>        // logic to turn the DVD player off<br>    }<br>}<br><br>class RemoteControl {<br>    method operateDevice(ElectronicDevice device) {<br>        device.turnOn()<br>        // Other operations...<br>        device.turnOff()<br>    }<br>}</pre><p>Now, you might ask, why bother with interfaces and polymorphism?</p><p>The utility of polymorphism is clear: one class can control diverse methods. One Universal remote control for all devices. Interfaces not only facilitate polymorphism but also address the multiple inheritance issue. Without delving too deep (a topic for another article), multiple inheritance allows a class to inherit methods from numerous classes. Java and C# for example prohibit multiple inheritance. However, they permit a class to implement multiple interfaces, drawing a distinction between “implementation” and “inheritance.”</p><p>(Note: Python does allow multiple inheritance, but it’s often best to use composition, aligning more with Python’s philosophy.)<br> <br> I hope you now have a better understanding of what polymorphism and interfaces are.</p><p>Now, why isn’t it common to hear about polymorphism and interfaces in <strong>Python</strong>? Why aren’t these topics frequently mentioned in YouTube tutorials, articles, and bootcamps related to Python?</p><p>In Python, polymorphism is inherent due to its dynamic nature (Python is a strongly dynamically-typed language) and the “duck typing” approach.</p><p>In languages like Java or C#, inheritance and interfaces are used to achieve polymorphism, and it’s necessary to specify explicitly which classes or interfaces are being used. In Python, if an object “walks like a duck and quacks like a duck, it is a duck”, meaning that an object doesn’t need to explicitly inherit from a particular class to be treated as an object of that type.</p><p>Duck typing is the principle that allows for the implicit implementation of polymorphism in Python. There’s no need to explicitly declare interfaces or return types. If an object has the necessary method or attribute, you can use it, regardless of the object’s class or inheritance hierarchy.</p><p>Look at better in the next example:</p><pre>class Dog:<br>    def talk(self):<br>        return &quot;Woof!&quot;<br><br>class Cat:<br>    def talk(self):<br>        return &quot;Meow!&quot;<br><br>def sound_animal(animal):<br>    return animal.talk()<br><br># Example usage:<br>dog = Dog()<br>cat = Cat()<br><br>print(sound_animal(dog))  # Output: Woof!<br>print(sound_animal(cat))  # Output: Meow!</pre><p>In this example, both the <strong>Dog and Cat</strong> classes have a <strong>talk()</strong> method. Even though there is no common base or interface defined, we can still pass them to the <strong><em>sound_animal</em></strong> function and expect a sound in return. This demonstrates polymorphism in Python.</p><p>Therefore, while in other languages ​​you need to be explicit about polymorphism using tools like inheritance and interfaces, in Python it is an implicit feature thanks to duck typing.</p><h3><strong>Emulating Interfaces with Abstract Classes:</strong></h3><p>Python doesn’t have interfaces in the traditional sense like Java or C#. However, we can emulate the behavior using abstract base classes and the abc module.</p><pre>from abc import ABC, abstractmethod<br><br>class Flyer(ABC):<br><br>    @abstractmethod<br>    def fly(self):<br>        pass<br><br>class Bird(Flyer):<br>    <br>    def fly(self):<br>        return &quot;The bird flaps its wings.&quot;<br><br>class Airplane(Flyer):<br>    <br>    def fly(self):<br>        return &quot;The airplane uses its engines.&quot;<br><br># Example usage:<br>bird = Bird()<br>plane = Airplane()<br><br>print(bird.fly())  # Output: The bird flaps its wings.<br>print(plane.fly())  # Output: The airplane uses its engines.</pre><p><strong>Explanation:</strong></p><p>1. The <strong><em>abc</em></strong> module in Python is used to work with abstract classes. <strong>“Abc</strong>” stands for “<strong>Abstract Base Class</strong>”.</p><p>2. <strong>Abstract Class and Abstract Method</strong>: A class with one or more abstract methods is termed an abstract class. An abstract class can contain both regular and abstract methods. An abstract method has a declaration but lacks an implementation. In the given example, Flyer is an abstract class, and fly is an abstract method.</p><p>3. <strong>Implementation</strong>: The<strong> Bird</strong> and Airplane classes inherit (or extend in python context) the Flyer abstract class. Since fly is an abstract method in Flyer, both Bird and Airplane classes must provide an implementation for this method.</p><p>Using the <strong><em>abc</em></strong> module and abstract classes in <strong>Python</strong>, we can emulate and establish contracts in a manner similar to how it’s done in Java or C#.</p><h3><strong>Control Remote Example in Python:</strong></h3><p>Considering our earlier analogy about the remote control:</p><pre>class RemoteControl(ABC):<br><br>    @abstractmethod<br>    def switch_on(self):<br>        pass<br><br>    @abstractmethod<br>    def switch_off(self):<br>        pass<br><br>class TV(RemoteControl):<br>    <br>    def switch_on(self):<br>        return &quot;TV is now ON.&quot;<br>    <br>    def switch_off(self):<br>        return &quot;TV is now OFF.&quot;<br><br>class SoundSystem(RemoteControl):<br>    <br>    def switch_on(self):<br>        return &quot;SoundSystem is now ON.&quot;<br>    <br>    def switch_off(self):<br>        return &quot;SoundSystem is now OFF.&quot;<br><br># Example usage:<br>tv = TV()<br>sound_system = SoundSystem()<br><br>print(tv.switch_on())  # Output: TV is now ON.<br>print(sound_system.switch_off())  # Output: SoundSystem is now OFF.</pre><p>Just as before, we defined a contract with our RemoteControl abstract class that any device (like TV or SoundSystem) must fulfill.</p><p>By recognizing and understanding these patterns in Python, you can appreciate how this language uniquely addresses OOP concepts in its own way. This understanding can also smooth out the transition if you ever decide to dive into languages like Java or C# that handle these concepts more explicitly.</p><p>This is slightly off-topic, but I wanted to mention it. In Python, by philosophy (it’s a philosophy, not a rule), there’s a tendency to favor composition over inheritance. Composition is another important concept in OOP. This preference for composition is another reason why we don’t often hear about polymorphism and interfaces in Python</p><h3><strong>Conclusion.</strong></h3><p>To conclude, polymorphism exists in Python, but it is inherent to the language; you use it, but you might not realize that you are doing so. On the other hand, interfaces don’t exist in Python in the same way they do in, for example, Java. However, we can emulate them using the abc module and abstract classes, which, in some scenarios, could be worthwhile.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1da1dba4e507" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>