<?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 Nitin Bhagat on Medium]]></title>
        <description><![CDATA[Stories by Nitin Bhagat on Medium]]></description>
        <link>https://medium.com/@jaiswalnitin054?source=rss-bf001e77cf6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QiGB6Y5vfCyr2sZJxxnArw.jpeg</url>
            <title>Stories by Nitin Bhagat on Medium</title>
            <link>https://medium.com/@jaiswalnitin054?source=rss-bf001e77cf6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:33:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaiswalnitin054/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[Dockerizing and Orchestrating a Microservices Architecture with Kubernetes: Part 3]]></title>
            <link>https://medium.com/@jaiswalnitin054/dockerizing-and-orchestrating-a-microservices-architecture-with-kubernetes-part-2-dfee32616218?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfee32616218</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 04:34:47 GMT</pubDate>
            <atom:updated>2024-03-03T09:13:58.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*QlSdO93BQ7pKt8LV0W8K5A.png" /><figcaption>Dockerizing and orchestration of node-based microservice</figcaption></figure><p>Let’s continue with dockerization and orchestration using Kubernetes of our microservices.</p><p>Let’s start with setting up monitoring and logging for the frontend service:</p><h3>7. Monitoring and Logging:</h3><p>What we do:</p><ul><li>Set up monitoring and logging for your microservices using tools like Prometheus, Grafana, and Fluentd.</li><li>Configure Kubernetes to collect and aggregate logs and metrics from your microservices.</li></ul><h4>Monitoring the Frontend Service</h4><ol><li>Install Prometheus and Grafana:</li></ol><ul><li>Follow the instructions on the <em>Prometheus website</em> to install Prometheus.</li><li>Follow the instructions on the <em>Grafana website </em>to install Grafana.</li></ul><p>2. Configure Prometheus to Scrape Metrics from the Frontend Service:</p><ul><li>Create a new file named frontend-prometheus.yaml and add the following content:</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: frontend-prometheus<br>spec:<br>  selector:<br>    app: frontend<br>  ports:<br>    - protocol: TCP<br>      port: 9090<br>      targetPort: 9090</pre><p>3. Deploy the Prometheus Service:</p><ul><li>Run the following command to deploy the Prometheus service for the frontend:</li></ul><pre>kubectl apply -f frontend-prometheus.yaml</pre><p>4. Configure Grafana to Visualize Metrics from Prometheus:</p><ul><li>Open Grafana in your web browser and log in using the default credentials (admin/admin).</li><li>Add a new Prometheus data source with the URL <a href="http://frontend-prometheus:9090.">http://frontend-prometheus:9090.</a></li></ul><p>5. Create a Dashboard in Grafana:</p><ul><li>Create a new dashboard in Grafana and add a graph panel to visualize the metrics from Prometheus.</li></ul><h4>Logging the Frontend Service</h4><ol><li>Install Fluentd:</li></ol><ul><li>Follow the instructions on the Fluentd website to install Fluentd.</li></ul><p>2. Configure Fluentd to Collect Logs from the Frontend Service:</p><ul><li>Create a new file named frontend-fluentd.yaml and add the following content:</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: frontend-fluentd<br>spec:<br>  selector:<br>    app: frontend<br>  ports:<br>    - protocol: TCP<br>      port: 24224<br>      targetPort: 24224</pre><p>3. Deploy the Fluentd Service:</p><ul><li>Run the following command to deploy the Fluentd service for the frontend:</li></ul><pre>kubectl apply -f frontend-fluentd.yaml</pre><p>4. Configure Fluentd to Forward Logs to a Centralized Logging System:</p><ul><li>Configure Fluentd to forward logs to a centralized logging system (e.g., Elasticsearch, Logstash, and Kibana).</li></ul><p>In this section, we set up monitoring and logging for the frontend service of our microservices application. We installed Prometheus and Grafana for monitoring, and Fluentd for logging. We configured Prometheus to scrape metrics from the frontend service, and Grafana to visualize these metrics. We also configured Fluentd to collect logs from the frontend service and forward them to a centralized logging system.</p><p>In the next section, we will set up a CI/CD pipeline for our microservices application.</p><h3>8. CI/CD Pipeline</h3><h4>Setting Up GitHub Actions</h4><ol><li>Create a GitHub Repository:</li></ol><ul><li>Create a new repository on GitHub for your microservices application.</li></ul><ol><li>Create a GitHub Actions Workflow:</li></ol><ul><li>In your GitHub repository, create a new directory named .github/workflows.</li><li>Create a new file named ci-cd.yml in the .github/workflows directory and add the following content:</li></ul><pre>name: CI/CD Pipeline<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br><br>      - name: Set up Node.js<br>        uses: actions/setup-node@v2<br>        with:<br>          node-version: &#39;14&#39;<br><br>      - name: Install dependencies<br>        run: npm install<br><br>      - name: Build Docker image<br>        run: |<br>          docker build -t frontend-service -f Dockerfile.frontend .<br>          docker build -t backend-service -f Dockerfile.backend .<br><br>      - name: Push Docker images to registry<br>        run: |<br>          echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin<br>          docker tag frontend-service ${{ secrets.DOCKER_REGISTRY }}/${{ secrets.DOCKER_USERNAME }}/frontend-service<br>          docker push ${{ secrets.DOCKER_REGISTRY }}/${{ secrets.DOCKER_USERNAME }}/frontend-service<br>          docker tag backend-service ${{ secrets.DOCKER_REGISTRY }}/${{ secrets.DOCKER_USERNAME }}/backend-service<br>          docker push ${{ secrets.DOCKER_REGISTRY }}/${{ secrets.DOCKER_USERNAME }}/backend-service<br><br>      - name: Deploy to Kubernetes<br>        run: |<br>          kubectl apply -f frontend-deployment.yaml<br>          kubectl apply -f frontend-service.yaml<br>          kubectl apply -f backend-deployment.yaml<br>          kubectl apply -f backend-service.yaml</pre><p>3. Configure GitHub Secrets:</p><ul><li>Go to your GitHub repository settings and navigate to “Secrets”.</li><li>Add the following secrets:</li><li>DOCKER_USERNAME: Your Docker Hub username.</li><li>DOCKER_PASSWORD: Your Docker Hub password.</li><li>DOCKER_REGISTRY: Your Docker Hub registry URL (e.g., docker.io).</li></ul><p>4. Commit and Push Changes:</p><ul><li>Commit the changes to your GitHub repository and push them to the main branch.</li></ul><p>In this section, we set up a CI/CD pipeline for our microservices application using GitHub Actions. We created a GitHub Actions workflow that runs on every push to the main branch. The workflow checks out the code, sets up Node.js, installs dependencies, builds Docker images, pushes the Docker images to Docker Hub, and deploys the microservices to Kubernetes. We also configured GitHub Secrets to securely store sensitive information. In the next section, we will summarize what we&#39;ve learned and achieved in this project.</p><h3>9. Summary:</h3><p>In this project, we created a microservices-based application using Node.js and Express.js. The application consists of two microservices: a “frontend” service that serves a basic HTML page, and a “backend” service that provides an API endpoint. We dockerized the microservices, deployed them to a Kubernetes cluster, and set up monitoring and logging using Prometheus, Grafana, and Fluentd. We also implemented a CI/CD pipeline using GitHub Actions to automate the building, testing, and deployment of the microservices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfee32616218" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing and Orchestrating a Microservices Architecture with Kubernetes: Part 2]]></title>
            <link>https://medium.com/@jaiswalnitin054/python-interview-prep-a378a7e2bdae?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a378a7e2bdae</guid>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 10:58:01 GMT</pubDate>
            <atom:updated>2024-03-03T09:00:45.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*QlSdO93BQ7pKt8LV0W8K5A.png" /><figcaption>Dockerizing and orchestration of node-based microservice</figcaption></figure><p>Let’s continue with dockerization and orchestration using Kubernetes of our microservices.</p><h3>4. Dockerizing the Microservices:</h3><p>What you do:</p><ul><li>Create Dockerfiles for each microservice to define their respective Docker images.</li><li>Build and push the Docker images to a container registry (e.g., Docker Hub, Google Container Registry, or Amazon ECR).</li></ul><h4>Dockerizing the Frontend Service</h4><ol><li>Create a Dockerfile:</li></ol><ul><li>In the ‘<em>microservice-app’</em> directory, create a new file named ‘<em>Dockerfile.frontend’</em> and add the following content:</li></ul><pre># Use the official Node.js 14 image as the base image<br>FROM node:14</pre><pre># Set the working directory inside the container<br>WORKDIR /app</pre><pre># Copy package.json and package-lock.json to the working directory<br>COPY package*.json ./</pre><pre># Install dependencies<br>RUN npm install</pre><pre># Copy the rest of the application code to the working directory<br>COPY . .</pre><pre># Expose port 3000<br>EXPOSE 3000</pre><pre># Command to run the application<br>CMD [&quot;node&quot;, &quot;frontend.js&quot;]</pre><p>2. Build the Docker Image:</p><ul><li>Run the following command to build the Docker image for the frontend service:</li></ul><pre>docker build -t frontend-service -f Dockerfile.frontend .</pre><p>3. Push the Docker Image to a Container Registry:</p><ul><li>If you haven’t already, create an account on a container registry (e.g., Docker Hub, Google Container Registry, or Amazon ECR).</li><li>Log in to the container registry using the command provided by the registry.</li><li>Tag the Docker image with the registry URL and repository name:</li></ul><pre>docker tag frontend-service &lt;registry-url&gt;/&lt;repository-name&gt;:frontend-service</pre><ul><li>Push the Docker image to the container registry:</li></ul><pre>docker push &lt;registry-url&gt;/&lt;repository-name&gt;:frontend-service</pre><h4>Dockerizing the Backend Service</h4><ol><li>Create a Dockerfile:</li></ol><ul><li>In the ‘<em>backend’</em> directory, create a new file named <em>‘Dockerfile.backend’</em> and add the following content:</li></ul><pre># Use the official Node.js 14 image as the base image<br>FROM node:14</pre><pre># Set the working directory inside the container<br>WORKDIR /app</pre><pre># Copy package.json and package-lock.json to the working directory<br>COPY package*.json ./</pre><pre># Install dependencies<br>RUN npm install</pre><pre># Copy the rest of the application code to the working directory<br>COPY . .</pre><pre># Expose port 4000<br>EXPOSE 4000</pre><pre># Command to run the application<br>CMD [&quot;node&quot;, &quot;backend.js&quot;]</pre><p>2. Build the Docker Image:</p><ul><li>Run the following command to build the Docker image for the backend service:</li></ul><pre>docker build -t backend-service -f Dockerfile.backend .</pre><p>3. Push the Docker Image to a Container Registry:</p><ul><li>If you haven’t already, create an account on a container registry (e.g., Docker Hub, Google Container Registry, or Amazon ECR).</li><li>Log in to the container registry using the command provided by the registry.</li><li>Tag the Docker image with the registry URL and repository name:</li></ul><pre>docker tag backend-service &lt;registry-url&gt;/&lt;repository-name&gt;:backend-service</pre><ul><li>Push the Docker image to the container registry:</li></ul><pre>docker push &lt;registry-url&gt;/&lt;repository-name&gt;:backend-service</pre><h3>5. Deploying Microservices to Kubernetes:</h3><p>What you do:</p><ul><li>Write Kubernetes deployment YAML files for each microservice to define how they should be deployed.</li><li>Create Kubernetes services to expose the microservices to each other and to external clients.</li><li>Deploy the microservices to your Kubernetes cluster.</li></ul><h4>Deploying the Frontend Service to Kubernetes</h4><ol><li>Create a Kubernetes Deployment YAML File:</li></ol><ul><li>In the microservices-app directory, create a new file named frontend-deployment.yaml and add the following content:</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: frontend-deployment<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: frontend<br>  template:<br>    metadata:<br>      labels:<br>        app: frontend<br>    spec:<br>      containers:<br>        - name: frontend<br>          image: &lt;registry-url&gt;/&lt;repository-name&gt;:frontend-service<br>          ports:<br>            - containerPort: 3000</pre><p>2. Create a Kubernetes Service:</p><ul><li>Create a new file named frontend-service.yaml and add the following content:</li></ul><pre>Create a Kubernetes Service:</pre><pre>Create a new file named frontend-service.yaml and add the following content:</pre><p>3. Deploy the Frontend Service:</p><ul><li>Run the following command to deploy the frontend service to your Kubernetes cluster:</li></ul><pre>kubectl apply -f frontend-deployment.yaml<br>kubectl apply -f frontend-service.yaml</pre><h4>Deploying the Backend Service to Kubernetes</h4><ol><li>In the backend directory, create a new file named backend-deployment.yaml and add the following content:</li></ol><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: backend-deployment<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: backend<br>  template:<br>    metadata:<br>      labels:<br>        app: backend<br>    spec:<br>      containers:<br>        - name: backend<br>          image: &lt;registry-url&gt;/&lt;repository-name&gt;:backend-service<br>          ports:<br>            - containerPort: 4000</pre><p>2. Create a Kubernetes Service:</p><ul><li>Create a new file named backend-service.yaml and add the following content:</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: backend-service<br>spec:<br>  selector:<br>    app: backend<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 4000<br>  type: LoadBalancer</pre><p>3. Deploy the Backend Service:</p><ul><li>Run the following command to deploy the backend service to your Kubernetes cluster:</li></ul><pre>kubectl apply -f backend-deployment.yaml<br>kubectl apply -f backend-service.yaml</pre><h3>6. Scaling and Load Balancing:</h3><p>What you do:</p><ul><li>Experiment with scaling your microservices horizontally by increasing the number of replicas.</li><li>Implement a load balancer (e.g., Kubernetes Service or Ingress) to distribute traffic among multiple instances of a microservice.</li></ul><h4>Scaling the Frontend Service</h4><ol><li>Scale the Frontend Deployment:</li></ol><ul><li>Run the following command to scale the frontend deployment to 3 replicas:</li></ul><pre>kubectl scale deployment frontend-deployment --replicas=3</pre><p>2. Verify the Scaling:</p><ul><li>Run the following command to check the status of the frontend deployment:</li></ul><pre>kubectl get deployment frontend-deployment</pre><ul><li>You should see that the number of replicas has been increased to 3.</li></ul><h4>Load Balancing the Frontend Service</h4><ol><li>Create a Kubernetes Service for Load Balancing:</li></ol><ul><li>Create a new file named frontend-loadbalancer.yaml and add the following content:</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: frontend-loadbalancer<br>spec:<br>  selector:<br>    app: frontend<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 3000<br>  type: LoadBalancer</pre><p>2. Deploy the Load Balancer Service:</p><ul><li>Run the following command to deploy the load balancer service for the frontend:</li></ul><pre>kubectl apply -f frontend-loadbalancer.yaml</pre><p>3. Verify the Load Balancer Service:</p><ul><li>Run the following command to get the external IP address of the load balancer service:</li></ul><pre>kubectl get svc frontend-loadbalancer</pre><ul><li>You should see an external IP address assigned to the service.</li></ul><h4>Scaling the Backend Service</h4><ol><li>Scale the Backend Deployment:</li></ol><ul><li>Run the following command to scale the backend deployment to 3 replicas:</li></ul><pre>kubectl scale deployment backend-deployment --replicas=3</pre><p>2. Verify the Scaling:</p><ul><li>Run the following command to check the status of the backend deployment:</li></ul><pre>kubectl get deployment backend-deployment</pre><ul><li>You should see that the number of replicas has been increased to 3.</li></ul><h4>Load Balancing the Backend Service</h4><ol><li>Create a Kubernetes Service for Load Balancing:</li></ol><ul><li>Create a new file named backend-loadbalancer.yaml and add the following content:</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: backend-loadbalancer<br>spec:<br>  selector:<br>    app: backend<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 4000<br>  type: LoadBalancer</pre><p>2. Deploy the Load Balancer Service:</p><ul><li>Run the following command to deploy the load balancer service for the backend:</li></ul><pre>kubectl apply -f backend-loadbalancer.yaml</pre><p>3. Verify the Load Balancer Service:</p><ul><li>Run the following command to get the external IP address of the load balancer service:</li></ul><pre>kubectl get svc backend-loadbalancer</pre><ul><li>You should see an external IP address assigned to the service.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a378a7e2bdae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Platform Django Backend(OpenAI API & Stripe)]]></title>
            <link>https://medium.com/@jaiswalnitin054/platform-django-backend-a13b634133cb?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13b634133cb</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 15:12:47 GMT</pubDate>
            <atom:updated>2024-02-08T06:27:15.957Z</atom:updated>
            <content:encoded><![CDATA[<p>Certainly! Let’s go through the process step by step to set up your Django project, including the OpenAI API key handling.</p><h3>Step 1: Setup Virtual Environment and Install Dependencies</h3><pre># Create a virtual environment<br>python -m venv myenv</pre><pre># Activate the virtual environment<br># On Windows<br>.\myenv\Scripts\activate<br># On Unix or MacOS<br>source myenv/bin/activate</pre><pre># Install Django, Stripe, and OpenAI<br>pip install django stripe openai</pre><h3>Step 2: Create a Django Project and App</h3><pre># Create a Django project<br>django-admin startproject fintech_project</pre><pre># Navigate to the project directory<br>cd fintech_project</pre><pre># Create a Django app<br>python manage.py startapp payment_gateway</pre><h3>Step 3: Configure Django Settings</h3><p>Edit fintech_project/settings.py:</p><pre># fintech_project/settings.py</pre><pre>INSTALLED_APPS = [<br>    # ...<br>    &#39;payment_gateway&#39;,<br>]</pre><pre># Add your Stripe and ChatGPT API keys<br>STRIPE_PUBLIC_KEY = &#39;your-stripe-public-key&#39;<br>STRIPE_SECRET_KEY = &#39;your-stripe-secret-key&#39;<br>OPENAI_API_KEY = &#39;your-openai-api-key&#39;</pre><h3>Step 4: Create utils.py for API Key Setup</h3><p>Create a file named utils.py in your payment_gateway app:</p><pre># payment_gateway/utils.py</pre><pre>import openai<br>from django.conf import settings</pre><pre>def setup_openai_api_key():<br>    openai.api_key = settings.OPENAI_API_KEY</pre><h3>Step 5: Update views.py to Import and Use setup_openai_api_key</h3><p>Modify your payment_gateway/views.py to import and use the setup_openai_api_key function</p><pre># payment_gateway/views.py</pre><pre>from django.shortcuts import render, redirect<br>from .models import Transaction, Payment<br>from .utils import setup_openai_api_key  # Import the setup function<br>import stripe<br>import openai</pre><pre>stripe.api_key = &#39;your-stripe-secret-key&#39;<br>setup_openai_api_key()  # Call the function to set up the OpenAI API key</pre><pre># ... (rest of your views)</pre><h3>Step 6: Define Models</h3><p>Edit payment_gateway/models.py:</p><pre># payment_gateway/models.py</pre><pre>from django.db import models</pre><pre>class Transaction(models.Model):<br>    amount = models.DecimalField(max_digits=10, decimal_places=2)<br>    description = models.TextField()<br>    timestamp = models.DateTimeField(auto_now_add=True)</pre><pre>    def __str__(self):<br>        return f&quot;${self.amount} - {self.description}&quot;</pre><pre>class Payment(models.Model):<br>    amount = models.DecimalField(max_digits=10, decimal_places=2)<br>    description = models.TextField()<br>    timestamp = models.DateTimeField(auto_now_add=True)<br>    stripe_payment_id = models.CharField(max_length=50, blank=True, null=True)</pre><pre>    def __str__(self):<br>        return f&quot;${self.amount} - {self.description}&quot;</pre><h3>Step 7: Make Migrations and Apply</h3><pre># Make migrations<br>python manage.py makemigrations</pre><pre># Apply migrations<br>python manage.py migrate</pre><h3>Step 8: Create Django Admin Panel</h3><p>Edit payment_gateway/admin.py:</p><pre># payment_gateway/admin.py</pre><pre>from django.contrib import admin<br>from .models import Transaction, Payment</pre><pre>admin.site.register(Transaction)<br>admin.site.register(Payment)</pre><h3>Step 9: Create Views and Templates</h3><p>Edit payment_gateway/views.py:</p><pre># payment_gateway/views.py</pre><pre>from django.shortcuts import render, redirect<br>from .models import Transaction, Payment<br>from .utils import setup_openai_api_key<br>import stripe<br>import openai</pre><pre>stripe.api_key = &#39;your-stripe-secret-key&#39;<br>setup_openai_api_key()</pre><pre># Your existing views here...</pre><pre>def chat_assistant(request):<br>    if request.method == &#39;POST&#39;:<br>        user_question = request.POST[&#39;user_question&#39;]</pre><pre>        # Use ChatGPT API to get a response<br>        response = openai.Completion.create(<br>            engine=&quot;text-davinci-002&quot;,<br>            prompt=f&quot;User: {user_question}\nAssistant:&quot;,<br>            temperature=0.7,<br>            max_tokens=150,<br>            n=1,<br>        )</pre><pre>        assistant_reply = response[&#39;choices&#39;][0][&#39;text&#39;]</pre><pre>        return render(request, &#39;payment_gateway/chat_response.html&#39;, {&#39;user_question&#39;: user_question, &#39;assistant_reply&#39;: assistant_reply})</pre><pre>    return render(request, &#39;payment_gateway/chat_form.html&#39;)</pre><p>Create HTML templates:</p><h4>payment_gateway/templates/payment_gateway/transaction_list.html</h4><pre>&lt;!-- payment_gateway/templates/payment_gateway/transaction_list.html --&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Transaction List&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Transaction List&lt;/h2&gt;<br>    &lt;ul&gt;<br>        {% for transaction in transactions %}<br>            &lt;li&gt;{{ transaction }}&lt;/li&gt;<br>        {% endfor %}<br>    &lt;/ul&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>payment_gateway/templates/payment_gateway/payment_form.html</h4><pre>&lt;!-- payment_gateway/templates/payment_gateway/payment_form.html --&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Make Payment&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Make Payment&lt;/h2&gt;<br>    &lt;form method=&quot;post&quot; action=&quot;{% url &#39;make_payment&#39; %}&quot;&gt;<br>        {% csrf_token %}<br>        &lt;label for=&quot;amount&quot;&gt;Amount:&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;amount&quot; required&gt;<br>        &lt;br&gt;<br>        &lt;label for=&quot;description&quot;&gt;Description:&lt;/label&gt;<br>        &lt;textarea name=&quot;description&quot; required&gt;&lt;/textarea&gt;<br>        &lt;br&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Pay Now&lt;/button&gt;<br>    &lt;/form&gt;</pre><pre>    &lt;p&gt;Need assistance? &lt;a href=&quot;{% url &#39;chat_assistant&#39; %}&quot;&gt;Chat with our Assistant&lt;/a&gt;&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>payment_gateway/templates/payment_gateway/payment_confirmation.html</h4><pre>&lt;!-- payment_gateway/templates/payment_gateway/payment_confirmation.html --&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Payment Confirmation&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Payment Confirmation&lt;/h2&gt;<br>    &lt;p&gt;Payment Successful!&lt;/p&gt;<br>    &lt;p&gt;Amount: ${{ payment.amount }}&lt;/p&gt;<br>    &lt;p&gt;Description: {{ payment.description }}&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>payment_gateway/templates/payment_gateway/chat_form.html</h4><pre>&lt;!-- payment_gateway/templates/payment_gateway/chat_form.html --&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Chat with Assistant&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Chat with Assistant&lt;/h2&gt;<br>    &lt;form method=&quot;post&quot; action=&quot;{% url &#39;chat_assistant&#39; %}&quot;&gt;<br>        {% csrf_token %}<br>        &lt;label for=&quot;user_question&quot;&gt;Ask a question:&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;user_question&quot; required&gt;<br>        &lt;br&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Ask&lt;/button&gt;<br>    &lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>payment_gateway/templates/payment_gateway/chat_response.html</h4><pre>&lt;!-- payment_gateway/templates/payment_gateway/chat_response.html --&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Chat Response&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Chat Response&lt;/h2&gt;<br>    &lt;p&gt;User&#39;s Question: {{ user_question }}&lt;/p&gt;<br>    &lt;p&gt;Assistant&#39;s Reply: {{ assistant_reply }}&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Step 10: Configure URLs</h3><p>Update payment_gateway/urls.py:</p><pre># payment_gateway/urls.py</pre><pre>from django.urls import path<br>from .views import transaction_list, make_payment, chat_assistant</pre><pre>urlpatterns = [<br>    path(&#39;transactions/&#39;, transaction_list, name=&#39;transaction_list&#39;),<br>    path(&#39;make-payment/&#39;, make_payment, name=&#39;make_payment&#39;),<br>    path(&#39;chat-assistant/&#39;, chat_assistant, name=&#39;chat_assistant&#39;),<br>]</pre><p>Include these URLs in the main urls.py of your project:</p><pre># fintech_project/urls.py</pre><pre>from django.contrib import admin<br>from django.urls import include, path</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;payments/&#39;, include(&#39;payment_gateway.urls&#39;)),<br>]</pre><h3>Step 11: Run the Development Server</h3><pre>python manage.py runserver</pre><p>Now, your Django fintech project is set up with features such as payment processing, transaction listing, and a chat-based assistant using the ChatGPT API. Visit the following URLs to explore the different functionalities:</p><ul><li>http://127.0.0.1:8000/admin/: Django admin panel for managing transactions and payments.</li><li>http://127.0.0.1:8000/payments/transactions/: View the list of transactions.</li><li>http://127.0.0.1:8000/payments/make-payment/: Make a payment.</li><li>http://127.0.0.1:8000/payments/chat-assistant/: Chat with the assistant.</li></ul><p>Remember to replace &#39;your-openai-api-key&#39;, &#39;your-stripe-secret-key&#39;, and &#39;your-stripe-public-key&#39; with your actual API keys.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13b634133cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing and Orchestrating a Microservices Architecture with Kubernetes: Part 1]]></title>
            <link>https://medium.com/@jaiswalnitin054/introduction-to-containers-w-docker-kubernetes-b9cb8c0e0372?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9cb8c0e0372</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 17:09:01 GMT</pubDate>
            <atom:updated>2024-03-02T17:19:02.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*QlSdO93BQ7pKt8LV0W8K5A.png" /><figcaption>Dockerizing and orchestration of node-based microservice</figcaption></figure><p>Here’s how I have documented the process sequentially:</p><p>1.Introduction to Microservices Architecture and Kubernetes<br>2. Setting Up Your Development Environment<br>3. Creating a Sample Microservices Application<br>4. Dockerizing the Microservices<br>5. Deploying Microservices to Kubernetes<br>6. Scaling and Load Balancing<br>7. Monitoring and Logging<br>8. CI/CD Pipeline<br>9. Conclusion</p><h3>1. Introduction to Microservices Architecture and Kubernetes:</h3><p>Microservices architecture is an approach to software development that structures an application as a collection of loosely coupled services. Each service is responsible for a specific business capability and can be developed, deployed, and scaled independently. This approach contrasts with the traditional monolithic architecture, where the entire application is developed and deployed as a single unit. It provides you with various benefits such as: Scalability, Flexibility, Resilience and Ease of deployment.</p><p>While Docker is an open-source platform that automates the deployment of applications inside containers (Containers are lightweight, portable, and self-sufficient units that encapsulate an application and its dependencies, allowing it to run consistently across different environments), Kubernetes is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. It provides a framework for deploying, managing, and scaling applications in a highly available and fault-tolerant manner.</p><p>Moreover, Kubernetes is an ideal platform for managing microservices-based applications, as it provides the necessary infrastructure to handle complex deployments, manage scaling, and provide built-in service discovery and load balancing. By combining Docker and Kubernetes, developers can build, deploy, and manage microservices-based applications more efficiently and effectively.</p><h3>2. Setting Up Your Development Environment:</h3><p>What you do:</p><ul><li>Install Docker and Kubernetes on your local machine.</li><li>Set up a Kubernetes cluster using Minikube(kind, k3d , etc. are alternatives).</li></ul><p>If you’re interested in following along, please create an account on each of these websites:</p><ul><li><a href="http://aws.amazon.com/"><em>Amazon Web Services</em></a></li><li><a href="https://hub.docker.com/"><em>Docker Hub</em></a></li></ul><h4>Setting Up Docker</h4><ol><li>Install Docker:</li></ol><ul><li>Go to the <a href="https://docs.docker.com/engine/install/ubuntu/"><em>Docker website</em></a> and download the Docker Desktop application for your operating system.</li><li>Follow the installation instructions provided by Docker.</li></ul><p>2. Verify Docker Installation:</p><ul><li>Open a terminal or command prompt and run the following command to verify that Docker is installed correctly:</li></ul><pre>docker --version</pre><h4>Setting Up Kubernetes</h4><p>Keep in mind that we here will be using it for free so that no costs incur on deployment unlike while using cloud-based services. We hence will use Minikube— It implements a local kubernetes cluster on your OS(linux here).</p><ol><li>Install Minikube (for local development):</li></ol><ul><li>Minikube is a tool that allows you to run a single-node Kubernetes cluster on your local machine.</li><li>Install Minikube by following the instructions(Installation guide) on the <a href="https://github.com/kubernetes/minikube?tab=readme-ov-file"><em>Minikube GitHub page</em></a>.</li></ul><p>2. Start Minikube:</p><ul><li>Open a terminal or command prompt and run the following command to start Minikube:</li></ul><pre>minikube start</pre><p>3. Verify Kubernetes Installation:</p><ul><li>Run the following command to verify that Minikube and Kubernetes are installed correctly:</li></ul><pre>kubectl version</pre><h3>3. Creating a Microservices Application:</h3><p>Let’s create a simple microservices application using Node.js and Express.js. This application will consist of two microservices: a “frontend” service that serves a basic HTML page, and a “backend” service that provides an API endpoint.</p><h4>Step 1: Create the Frontend Service</h4><ol><li>Create a New Directory:</li></ol><p>Open a terminal or command prompt and create a new directory for your project:</p><pre>mkdir microservices-app<br>cd microservices-app</pre><p>2. Initialize a New Node.js Project:</p><p>Run the following command to initialize a new Node.js project:</p><pre>npm init -y</pre><p>3. Install Express.js:</p><p>Run the following command to install Express.js:</p><pre>npm install express</pre><p>4. Create the Frontend Service:</p><p>Create a new file named ‘<em>frontend.js</em>’ and add the following code:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;&lt;h1&gt;Welcome to the Frontend Service!&lt;/h1&gt;&#39;);<br>});<br><br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Frontend Service is running on port 3000&#39;);<br>});</pre><p>5. Run the Frontend Service:</p><p>Run the following command to start the frontend service:</p><pre>node frontend.js</pre><p>6. Test the frontend service:</p><p>Open a web browser and navigate to ‘http://localhost:3000&#39;. You should see the message &quot;Welcome to the Frontend Service!&quot;.</p><h4>Step 2: Create the Backend Service</h4><ol><li>Create a New Directory for the Backend Service:</li></ol><p>Open a terminal or command prompt and create a new directory for the backend service:</p><pre>mkdir backend<br>cd backend</pre><p>2. Initialize a New Node.js Project:</p><p>Run the following command to initialize a new Node.js project:</p><pre>npm init -y</pre><p>3. Install Express.js:</p><p>Run the following command to install Express.js:</p><pre>npm install express</pre><p>4. Create the Backend Service:</p><p>Create a new file named <em>backend.js</em> and add the following code:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/api&#39;, (req, res) =&gt; {<br>  res.json({ message: &#39;Welcome to the Backend Service!&#39; });<br>});<br><br>app.listen(4000, () =&gt; {<br>  console.log(&#39;Backend Service is running on port 4000&#39;);<br>});</pre><p>5. Run the Backend Service:</p><p>Run the following command to start the backend service:</p><pre>node backend.js</pre><p>6. Test the Backend Service:</p><ul><li>Open a web browser and navigate to ‘http://locahost:4000/api’. You should see the message ‘Welcome to the backend service!’.</li></ul><p>In the next section, we will dockerize these microservices and deploy them to Kubernetes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9cb8c0e0372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevOps on AWS: code, build and test(Part-2)]]></title>
            <link>https://medium.com/@jaiswalnitin054/devops-on-aws-code-and-build-part-2-dc69185d4602?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc69185d4602</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 15:38:53 GMT</pubDate>
            <atom:updated>2024-01-24T15:53:37.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exercise: Testing the Application</h3><p>In this exercise, you will return to the AWS Cloud9 instance and run the local build for the project. The local build contains linting (or static analysis) of the code and unit tests. Next, you will run an integration test. The integration test finds the API Gateway Websocket endpoint, and it simulates a player completing a game. You will then add a simple feature to the code. Finally, you will fix the unit tests and commit the changes to your repository.</p><h3>Task 1: Running unit tests</h3><p>In this task, you run unit tests against the application code. You then view the reports that are outputted from these tests.</p><ol><li>In your <strong>AWS Cloud9</strong> terminal, make sure you are still in the trivia-app folder. The prompt should also show the top-level Git branch.</li></ol><pre>cd ~/environment/trivia-app</pre><p>2. Install the backend code requirements and the unit test requirements by using pip3 to run the following commands.</p><pre>pip3 install -U -r back-end-python/gameactions/requirements.txt<br>pip3 install -U -r back-end-python/tests/requirements.txt<br>./local_build.sh</pre><p>You should see the code rating after pylint does its static analysis:</p><pre>------------------------------------<br>Your code has been rated at 10.00/10</pre><p>Then, pytest runs its unit tests, which are shown like the following example:</p><pre>back-end-python/tests/unit/test_handler.py .........</pre><p>It will also output a coverage report in HTML, which is in /trivia-app/htmlcov.</p><p>3. In the htmlcov folder, right-click the index.html file and view the coverage report by choosing <strong>Preview</strong>.</p><h3>Task 2: Running the integration test</h3><p>For this task, you run an integration test against the application code.</p><ol><li>Start the integration test (which will simulate a game) by running the following command.</li></ol><pre>AWS_SAM_STACK_NAME=trivia-app pytest -s back-end-python/tests/integration/test_api_gateway.py</pre><p>The integration test uses the AWS SAM stack to find the Websocket endpoint, so the stack is passed in the AWS_SAM_STACK_NAME environment variable.</p><p>At the end of the test, you should see the following message: <strong><em>1 passed</em></strong></p><h3>Task 3: Updating the code and unit tests</h3><p>In this task, you update the application code to change the score value from <em>10</em> to <em>20</em>. You also update the unit test code.</p><ol><li>Open the trivia-app/back-end-python/gameactions/app.py file.</li><li>Scroll down to the trivia_calculate_scores function.</li><li>Update the code so the game increments the score by 20 instead of by 10. Locate score += 10 and change it to score += 20. Make sure to save the file.</li></ol><pre>score += 20</pre><p>4. Verify that you left the code in a stable state by running the ./local_build.sh command.</p><p>At the top of the failure report, you should see that the test_trivia_calculate_scores_correct test failed:</p><pre><br><br>=============================================== FAILURES ============================================================================================<br>_________________________________ test_trivia_calculate_scores_correct ______________________________________________________________________________</pre><p>You also need to update the unit test to match the new score.</p><p>5. Open the trivia-app/back-end-python/tests/unit/test_handler.py file.</p><p>6. Find the test_trivia_calculate_scores_correct function.</p><p>7. In the function’s TABLE.update_item.assert_called_with call, find the AttributeUpdates field and update the Value from 10 to 20.</p><pre>AttributeUpdates={&#39;score&#39;: {&#39;Value&#39;: 20, &#39;Action&#39;: &#39;PUT&#39;}}</pre><p>8. You must also update app.MANAGEMENT.post_to_connection.assert_has_calls (which tests API Gateway Websocket calls). Change the value of score from 10 to 20.</p><pre>mock.call(Data=&#39;{&quot;action&quot;: &quot;playerlist&quot;, &quot;players&quot;: [{&quot;connectionId&quot;: &quot;connection-1&quot;, &quot;playerName&quot;: &quot;AliceBlue&quot;, &quot;score&quot;: 20, &quot;currentPlayer&quot;: true}]}&#39;, ConnectionId=&#39;connection-1&#39;),</pre><p>9. Save the file and re-run ./local_build.sh. The test summary should again show that everything passed.</p><h3>Task 4: Committing to source control through the AWS Cloud9 GUI or the AWS CLI</h3><p>In this task, you commit the changes from the previous tasks to your code repository. <em>You can commit the code by using either the </em><strong><em>AWS Cloud9 GUI</em></strong><em>, or AWS CLI commands in the </em><strong><em>AWS Cloud9 terminal</em></strong>.</p><ol><li>In the menu, at the left of <strong>AWS Cloud9</strong>, choose the source control icon:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/42/0*5qZPAcqll3gSsJtr.PNG" /></figure><p>2. Under <strong>Changes</strong>, select either the app.py or test_handler.py file to view the diffs between the original files and your changes.</p><p>3. Under <strong>Changes</strong>, stage the changes in app.py and test_handler.py for a commit by placing the pointer over the file name and choosing the stage icon (<strong>+</strong>) for the file. The files should now appear under <strong>Staged Changes</strong>.</p><p>4. In the <strong>Source Control</strong> pane, at the right side of the <strong>trivia-app</strong> heading, left-click paper scroll icon and choose <strong>Commit</strong>. Choose <strong>Yes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*AsZmSWv3c1lMbJ7C.PNG" /></figure><p>5. Under the <strong>trivia-app</strong> heading, enter the following commit message and press Enter: Scores now increment by 20</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/0*fN9eFJwVu51hHha-.PNG" /></figure><p>6. In the <strong>trivia-app</strong> heading, left-click the paper scroll icon and choose <strong>Push to…</strong>. When prompted to select a remote, choose the remote named <strong>origin</strong>.</p><h4>Commit changes through the AWS CLI ?</h4><h3>Task 4: Committing to source control through the AWS CLI</h3><ol><li>In <strong>AWS Cloud9</strong>, you can also use the AWS CLI to commit the changes to AWS CodeCommit by running the following command:</li></ol><pre>git add *<br>git commit -m &quot;Scores now increment by 20&quot;<br>git push origin main</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc69185d4602" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ShopStop: A Simple Ecommerce project Guide]]></title>
            <link>https://medium.com/@jaiswalnitin054/shopstop-a-simple-ecommerce-project-guide-ad8baaf258b3?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8baaf258b3</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 06:20:23 GMT</pubDate>
            <atom:updated>2024-02-02T10:58:16.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKNOYWp_m7KPB0dTUqeEDg.png" /><figcaption>MinMerch Clothing</figcaption></figure><h4>Step 1:</h4><p><strong>Project Setup — Frontend(React, HTML, CSS)</strong><br>1. Initialize new project</p><p>2. Create components for main pages(eg. home, product listing, product details, checkout, etc.)</p><p><strong>Backend(Node.js)</strong></p><ol><li>Initialize a New Node.js project</li></ol><p>2. Install necessary dependencies</p><p>3. setup a basic <em>express server</em> with <em>routes</em> for handling products and others.</p><p><strong>Database (MongoDB)</strong></p><ol><li>Setup free MongoDB Atlas account (mongodb.com/cloud/atlas) and create a new cluster.</li><li><em>Connect</em> your Node.js server to MongoDB using <em>Mongoose</em>.</li></ol><h4>Step 2:</h4><p>Implement Ecommerce Features.</p><p>Frontend:</p><ol><li>Implement product listing and product details pages.</li><li>Create a simple shopping cart using <em>React context</em> or <em>state management</em>.</li><li>Design a checkout page with essential info(shipping details, Payment, etc.)</li></ol><p>Backend:</p><ol><li>Implement <em>CRUD</em> operations for products and orders.</li><li>Set up <em>API routes</em> to handle product listing, product details, and order placement.</li></ol><h4>Step 3:</h4><p>Integration of Real-Time Features.</p><ol><li>Explore <em>Websocket</em> technology for real-time features.</li><li>Implement <em>real-time updates</em> for order status and/or notifications.</li></ol><h4>Step 4:</h4><p>Optimize and Continous Development(CD).</p><ol><li>Setup <em>linting</em> and <em>code formatting</em> for both frontend and backend.</li><li>Explore <em>Gitlab</em> for version control and CI/CD integration.</li></ol><h4>Step 5:(optional)</h4><p>AWS cloud Integration.</p><ol><li><em>Host</em> your (static) web application on <em>AWS S3</em> for static content.</li><li>Set up a <em>Node.js server</em> on an <em>EC2 instance</em>.</li><li>Explore <em>AWS RDS</em> for a managed <em>database service</em>.</li><li>Integrate <em>AWS lambda</em> and <em>API Gateway</em> for <em>serverless functions</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8baaf258b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevOps on AWS: code, build and test(Part-1)]]></title>
            <link>https://medium.com/@jaiswalnitin054/how-an-application-is-deployed-with-aws-77bcac1f0b21?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/77bcac1f0b21</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 07:05:09 GMT</pubDate>
            <atom:updated>2024-03-02T17:26:33.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*WOaNVibIbyk1UPz9hTtdSw.png" /><figcaption>aws-devops</figcaption></figure><p>In this exercise, you will create the following resources:</p><ul><li>AWS Cloud9 environment</li><li>Amazon Simple Storage Service (Amazon S3) bucket</li><li>Amazon API Gateway REST API</li><li>Amazon DynamoDB table</li><li>AWS Step Functions state machine</li><li>AWS Lambda functions</li></ul><p><strong>The final exercise includes instructions to delete all the resources that you create in the exercises.</strong></p><h3>Setting Up Your Development Environment</h3><p>In a production environment, you would normally create a customer managed policy in AWS Identity and Access Management (IAM). Customer managed policies provide more precise control over your policies than policies that AWS manages. This policy would then have permissions that are specific to the AWS resources you need. You would also attach this policy to a new user and log in to the AWS Management Console with that new user. However, because you are working in an exercise environment, those steps were omitted.</p><p>In this exercise, you will start by creating an AWS Cloud9 environment for your development environment. In this environment, you will download and extract the source code that you will use in this course. You will deploy the application’s backend infrastructure by using the AWS Serverless Application Model Command Line Interface (AWS SAM CLI). You will use AWS SAM to create all the resources that host the backend of the application: an Amazon API Gateway gateway, AWS Lambda functions, an Amazon DynamoDB table, and an AWS Step Functions state machine. You will also deploy the application frontend: a React web application that’s hosted on an S3 bucket, which acts as the web server. After the application is up and running, you will put the application under source control by using AWS CodeCommit.</p><h3>Task 1: Creating an AWS Cloud9 environment and downloading the application</h3><p>For this task, you create an AWS Cloud9 environment for use as your development environment. You also download the pre-built application on to the AWS Cloud9 instance.</p><ol><li>Choose <strong>Services</strong> and search for <strong>Cloud9</strong>. <em>Make sure you are in the Oregon </em><strong><em>(US-West-2)</em></strong><em> Region</em>.</li><li>Choose <strong>Create environment</strong>.</li><li>For <strong>Name</strong>, enter trivia-app, and choose <strong>Next step</strong>.</li><li>Keep the default <strong>Environment settings</strong> and choose <strong>Next step</strong>.</li><li>Choose <strong>Create environment</strong>.</li><li>Download the application through the <strong>AWS Cloud9</strong> terminal by running the following command:</li></ol><pre>wget https://aws-tc-largeobjects.s3.us-west-2.amazonaws.com/DEV-AWS-MO-DevOps-C1/downloads/trivia-app.zip -O ~/trivia-app.zip<br>unzip -o ~/trivia-app.zip</pre><h3>Task 2: Creating the backend infrastructure</h3><p>In this task, you deploy the application stack by using the AWS SAM and the AWS CLI. You also make a few minor configuration changes.</p><ol><li>In the AWS Cloud9 terminal, change the directory to the trivia-app folder and use AWS SAM to build the template.yaml file.</li></ol><pre>cd trivia-app<br>sam build<br>sam deploy --guided</pre><p><strong>AWS SAM settings:</strong> For the <strong>Stack Name</strong>, make sure to copy trivia-app and paste it. However, for the other entries, accept the default selections by pressing Enter or Return.</p><pre>Stack Name [sam-app]: trivia-app<br>AWS Region [us-west-2]: &lt;Press Enter or Return&gt;<br>#Shows you resources changes to be deployed and require a &#39;Y&#39; to initiate deploy<br>Confirm changes before deploy [y/N]: &lt;Press Enter or Return&gt;<br>#SAM needs permission to be able to create roles to connect to the resources in your template<br>Allow SAM CLI IAM role creation [Y/n]: &lt;Press Enter or Return&gt;<br>Save arguments to configuration file [Y/n]: &lt;Press Enter or Return&gt;<br>SAM configuration file [samconfig.toml]: &lt;Press Enter or Return&gt;<br>SAM configuration environment [default]: &lt;Press Enter or Return&gt;</pre><p>You should get confirmation that the stack was created successfully.</p><pre>Successfully created/updated stack - trivia-app in us-west-2</pre><p>2. From the <strong>Outputs</strong> table in the terminal output, copy the Websocket <strong>Value</strong>. It should look similar to the following example:</p><pre>wss://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/Prod</pre><h3>Task 3: Testing the frontend on AWS Cloud9</h3><p>In this task, you install Node package manager (NPM) dependencies. You also preview the application in the AWS Cloud9 environment.</p><ol><li>Update the trivia-app/front-end-react/src/config.js file with the Websocket endpoint that you copied previously. Make sure to save the file.</li><li>In <strong>AWS Cloud9</strong>, set the Node version to the v16 (codename: Gallium).</li></ol><pre>nvm install lts/gallium<br>nvm alias default lts/gallium</pre><p>3. Change to the front-end-react directory and install the NPM dependencies.</p><pre>cd front-end-react/<br>npm install<br>npm run start</pre><p><strong>Note:</strong> There is currently a <a href="https://github.com/webpack/webpack/issues/14532">known issue</a> with the dependency webpack under Node v17. If you see an error containing code: &#39;ERR_OSSL_EVP_UNSUPPORTED&#39; ensure you are running the exercise with Node v16.</p><p>After the NPM installation finishes, you might see NPM warnings, but it’s OK to proceed.</p><p>4. In the AWS Cloud9 menu bar, choose <strong>Preview</strong> and choose <strong>Preview Running Application</strong>. Feel free to play around with the game.</p><p>5. Finally, in the <strong>AWS Cloud9</strong> terminal, close the previewed application and end the running NPM server by sending a SIGINT (Ctrl+C).</p><h3>Task 4: Deploying the frontend to an S3 bucket</h3><p>For this task, you deploy the application to a new S3 bucket, which will act as the web server.</p><ol><li>Create a uniquely named Amazon Simple Storage Service (Amazon S3) bucket. For the bucket name, you could use your initials, a set of numbers, and the string <em>trivia-app-bucket</em>, similar to this example: &lt;your_initials&gt;&lt;numbers&gt;-trivia-app-bucket.</li></ol><pre>aws s3 mb s3://&lt;your_initials&gt;&lt;numbers&gt;-trivia-app-bucket/<br>npm run build<br>aws s3 sync --acl public-read build s3://&lt;your_initials&gt;&lt;numbers&gt;-trivia-app-bucket/</pre><p><strong>Note:</strong> If the bucket name you entered already exists, change the numbers and try to create the bucket again.</p><p>2. View the application that’s hosted on your bucket by using the application URL, which includes the bucket name and <em>index.html</em>. The URL should look similar to the following example: https://&lt;your_initials&gt;&lt;numbers&gt;-trivia-app-bucket.s3.amazonaws.com/index.html.</p><h3>Task 5: Putting the application under source control</h3><p>In this final task, you add source control to the application by using AWS CodeCommit to set up a new repository. You then use Git within AWS Cloud9 to commit the code changes to the repository.</p><ol><li>At the left on the menu bar, choose <strong>AWS Cloud9</strong> and choose <strong>Go To Your Dashboard</strong>.</li><li>Choose <strong>Services</strong> and search for <strong>CodeCommit</strong>.</li><li>Choose <strong>Create repository</strong>.</li><li>For the <strong>Repository name</strong>, enter trivia-app and then choose <strong>Create</strong>.</li><li>Switch back to the <strong>AWS Cloud9</strong> terminal window.</li><li>Configure Git with your name and email address.</li></ol><pre>git config --global user.name &quot;&lt;REPLACE_WITH_YOUR_NAME&gt;&quot;<br>git config --global user.email &lt;REPLACE_WITH_YOUR_EMAIL&gt;</pre><p>7. In the terminal, initialize your repository, create a branch and a commit, and push the code to the repository.</p><pre>cd ~/environment/trivia-app/<br>git init<br>git checkout -b main<br>git add .<br>git commit -m &quot;initial commit&quot;<br>git remote add origin codecommit://trivia-app<br>git push origin main</pre><p>The following list provides explanations of each Git command:</p><ul><li>git init - Initialize a Git repository.</li><li>git checkout -b main - Create a branch named main, and check out (switch to) the branch.</li><li>git add - Adds all the files to the Git index. The files are now staged for a commit.</li><li>git commit - Creates a commit in the Git log with a commit message.</li><li>git remote add origin - Create a remote named origin. A remote is how Git tracks the <em>remote</em> repository that is hosted in CodeCommit. The codecommit:// prefix tells Git to use the <a href="https://aws.amazon.com/about-aws/whats-new/2020/03/aws-codecommit-introduces-open-source-remote-helper/">CodeCommit remote helper</a>.</li><li>git push - Update the remote named origin with the main branch.</li></ul><p>Thank you for following till the end. Kindly let me know if you want to have further parts via email. Get in touch via Medium or email me at bhagatnitin254@gmail.com. Good Luck with the practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77bcac1f0b21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS-Localstack to Host a Static Website and Create AWS S3 bucket for storage]]></title>
            <link>https://medium.com/@jaiswalnitin054/use-of-free-tier-aws-to-develop-our-project-9b704eae48d0?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b704eae48d0</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 15:51:01 GMT</pubDate>
            <atom:updated>2024-01-24T05:24:07.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rd5HvcTy0dPLPN5pAgvkwg.png" /><figcaption>Localstack — free tier AWS emulator</figcaption></figure><h4>Why LocalStack?</h4><p>LocalStack is a cloud service emulator that runs in a single container on your laptop or in your CI environment. With LocalStack, you can <strong>run your AWS applications or Lambdas entirely on your local machine without connecting to a remote cloud provider</strong>! To begin, we’ll establish an S3 bucket and simulate deploying a static website to observe its functionality, mirroring the experience of deploying it on AWS S3.</p><p>In summary, LocalStack is a tool for local development and testing purposes, providing a local environment with replicated AWS services.</p><p>Can one use LocalStack without Docker?</p><p>By default, the LocalStack CLI starts the LocalStack runtime inside a Docker container.</p><h3>Integrating AWS into Your App using LocalStack</h3><h4>Step 1: Install LocalStack</h4><p>1.1. Open a terminal and create a virtual environment using Python’s virtualenv:</p><pre>python -m virtualenv venv</pre><p>1.2. Activate the virtual environment:</p><pre>. venv/bin/activate</pre><p>1.3.1. Install LocalStack using pip:</p><pre>pip install localstack</pre><ol><li>3.2. Alternatively, run LocalStack with Docker.</li></ol><p>Having Docker installed and making sure docker daemon running, run following command:</p><pre>docker run --rm -it -p 4566:4566 -p 4510-4559:4510-4559 localstack/localstack</pre><h4>Step 2: Configure AWS CLI</h4><p>2.1. Install AWS CLI. Visit AWS CLI Docs, find the AWS CLI MSI installer for Windows, and run the setup.</p><p><strong>To install</strong> the AWS CLI, run the following commands.</p><pre>$ curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>unzip awscliv2.zip<br>sudo ./aws/install</pre><p>You can now run: /usr/local/bin/aws — version. This should give something like following:<br><em>aws-cli/2.15.13 Python/3.11.6 Linux/5.15.0–91-generic exe/x86_64.ubuntu.20 prompt/of</em>f</p><p>2.2. After installation, configure the CLI using the following command:</p><pre>aws configure</pre><p>Provide the following information:</p><ul><li>AWS Access Key ID: test</li><li>AWS Secret Access Key: test</li><li>Default region name: us-east-1</li><li>Default output format: [None]</li></ul><h4>Step 3: Start LocalStack</h4><p>3.1. Start LocalStack using the following command:</p><pre>localstack start -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*i2M61KDyf2X4AGP7fgMT_g.png" /><figcaption>LocalStack start output</figcaption></figure><p>This will start LocalStack on localhost port 4566.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qi9BaQAZlNr_lfRI_eA6lw.png" /><figcaption>LocalStack — localhost:4566/ browser output</figcaption></figure><p><strong>Additionally, <em>Logs and Debugging</em>:</strong> If you encounter any issues or if you want to see more details about the running services, you can inspect the logs using:</p><pre>localstack logs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*F5rguOiAJ9A5tTf_UmEeyw.png" /><figcaption>LocalStack Logs output</figcaption></figure><h4>Step 4: Create an S3 Bucket</h4><p>4.1. Create an S3 bucket using the following command:</p><pre>aws --endpoint-url=http://localhost:4566 s3api create-bucket --bucket testbucket</pre><p>4.2. List available buckets:</p><pre>aws --endpoint-url=http://localhost:4566 s3api list-buckets</pre><p>4.3. Create a <em>test.txt</em> file (manually inside venv dir) Copy a test file to the created bucket:</p><pre>aws --endpoint-url=http://localhost:4566 s3 cp test.txt s3://testbucket</pre><p>4.4. Verify the file is uploaded:</p><pre>aws --endpoint-url=http://localhost:4566 s3api list-objects --bucket testbucket</pre><h4>Step 5: Host a Static Website</h4><p>5.1. Prepare index.html (and complementary CSS or other files) and error.html files in a folder called website.</p><p>5.2. Create a bucket_policy.json file with the following code in the <em>root dir</em>.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::testbucket/*&quot;<br>        }<br>    ]<br>}</pre><p>5.3. Sync the website folder to the S3 bucket:</p><pre>aws --endpoint-url=http://localhost:4566 s3 sync .\website\ s3://testbucket</pre><p>5.4. Enable static website hosting on the bucket:</p><pre>aws --endpoint-url=http://localhost:4566 s3 website s3://testbucket/ --index-document index.html --error-document error.html</pre><h4>Step 6: View the Hosted Website</h4><p>6.1. Open your browser and navigate to:</p><pre>http://testbucket.s3website.localhost.localstack.cloud:4566/testbucket/index.html<br><br>OR<br><br>https://localhost.localstack.cloud:4566/testbucket/index.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPMkFcV_V_xLSIkxs4xdCA.png" /></figure><p>You should now see the hosted website.</p><p><strong>Should/Do we stop LocalStack manually?</strong></p><p>Yes, when you start LocalStack in detached mode (with the -d flag), it runs in the background until you manually stop it. The LocalStack services will continue to be available on http://localhost:4566 until you either stop it or terminate the Docker container.</p><p><em>To stop LocalStack</em>, you can use the following command in your terminal:</p><pre>localstack stop</pre><p>This will send a stop signal to the LocalStack process, and it will gracefully shut down. If you started LocalStack with the -d flag, you&#39;ll regain control of the terminal after stopping LocalStack.</p><p>If you prefer to <em>stop the LocalStack Docker container directly</em>, you can use the following Docker command:</p><pre>docker stop $(docker ps -q --filter ancestor=localstack/localstack)</pre><p>This command finds the running LocalStack container and stops it. After stopping LocalStack, the services will no longer be available, and you can close the terminal or continue with other tasks.</p><p>Keep in mind that LocalStack is designed for local development and testing, so it’s up to you when to start and stop it based on your workflow. If you’re done with your development or testing session, it’s a good practice to stop LocalStack to free up resources.</p><h4>Integrating AWS into Your React and Node.js E-commerce Web App using LocalStack:</h4><p><a href="https://medium.com/@jaiswalnitin054/aws-hosting-of-your-reactjs-project-0c35881f6802">Click here</a></p><h4>Conclusion:</h4><p>LocalStack provides a convenient way to emulate AWS services for local development and testing. By following these steps, you can integrate AWS services into your React and Node.js e-commerce web app, allowing you to practice and develop hands-on experience without incurring costs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b704eae48d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming (OOP) concept in Python]]></title>
            <link>https://medium.com/@jaiswalnitin054/simulate-tracking-robot-complete-step-by-step-guide-c149231d8e1d?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c149231d8e1d</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[control]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[cmake]]></category>
            <category><![CDATA[robots]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 15:44:48 GMT</pubDate>
            <atom:updated>2024-03-04T09:27:15.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*bjYr_CDLaJNIODSutKJKzg.png" /><figcaption>OOP-in-Python</figcaption></figure><p>Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of “objects,” which can contain data in the form of fields (also known as attributes or properties) and code in the form of procedures (also known as methods). Python is an object-oriented programming language, and it supports OOP principles such as encapsulation, inheritance, and polymorphism.</p><h3>Structure of object-oriented programming</h3><p>Object-oriented programming contains various structures, known as the building blocks of OOP. These structures include:</p><ul><li><strong>Class:</strong> A class is a data type that provides a framework for creating objects. You can define a class to create multiple objects without writing additional code.</li><li><strong>Object:</strong> In OOP, an object represents an instance, or creation, of a class. Objects define specific data, such as properties and behaviors, to implement code.</li><li><strong>Method:</strong> A method is a function that performs a task or action. For example, a method may return information about an object’s data.</li><li><strong>Attribute:</strong> This structure stores information about an object and defines its state. You can define an attribute as part of the class.</li></ul><p>Let’s start with a simple example to understand the basics of OOP in Python:</p><pre>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def greet(self):<br>        print(f&quot;Hello, my name is {self.name} and I am {self.age} years old.&quot;)<br><br># Create an instance of the Person class<br>person1 = Person(&quot;Alice&quot;, 30)<br><br># Accessing attributes<br>print(person1.name)  # Output: Alice<br>print(person1.age)   # Output: 30<br><br># Calling methods<br>person1.greet()  # Output: Hello, my name is Alice and I am 30 years old.</pre><p>In this example, we define a Person class with an __init__ method (also known as a constructor) that initializes the name and age attributes of the object. We also define a greet method that prints a greeting message using the name and age attributes.</p><p>To create an instance of the Person class, we use the class name followed by parentheses, passing the required arguments to the __init__ method. We can then access the attributes and call the methods of the object using the dot notation (object.attribute or object.method()).</p><h3>Four principles of OOP:</h3><h3>Inheritance:</h3><p>Inheritance is a mechanism in which a new class is derived from an existing class. The new class inherits the attributes and methods of the existing class and can also have its own attributes and methods.</p><pre>class Student(Person):<br>    def __init__(self, name, age, student_id):<br>        super().__init__(name, age)<br>        self.student_id = student_id<br><br>    def study(self):<br>        print(f&quot;{self.name} is studying.&quot;)<br><br># Create an instance of the Student class<br>student1 = Student(&quot;Bob&quot;, 25, &quot;12345&quot;)<br><br># Accessing inherited attributes<br>print(student1.name)        # Output: Bob<br>print(student1.age)         # Output: 25<br>print(student1.student_id)  # Output: 12345<br><br># Calling inherited methods<br>student1.greet()  # Output: Hello, my name is Bob and I am 25 years old.<br>student1.study()  # Output: Bob is studying.</pre><p>In this example, we define a Student class that inherits from the Person class. The Student class has its own __init__ method that calls the __init__ method of the Person class using super(). The Student class also has a study method that prints a message indicating that the student is studying.</p><h3>Polymorphism:</h3><p>Polymorphism is the ability of different objects to respond to the same message (method call) in different ways. In Python, polymorphism is achieved through method overriding.</p><pre>class Dog:<br>    def speak(self):<br>        print(&quot;Woof!&quot;)<br><br>class Cat:<br>    def speak(self):<br>        print(&quot;Meow!&quot;)<br><br># Create instances of the Dog and Cat classes<br>dog = Dog()<br>cat = Cat()<br><br># Call the speak method on the Dog and Cat objects<br>dog.speak()  # Output: Woof!<br>cat.speak()  # Output: Meow!</pre><p>In this example, both the Dog and Cat classes have a speak method. When we call the speak method on a Dog object, it prints &quot;Woof!&quot;, and when we call the speak method on a Cat object, it prints &quot;Meow!&quot;. This demonstrates polymorphism, as the same method call (speak()) produces different behavior depending on the object.</p><h3>Encapsulation:</h3><p>Encapsulation is the bundling of data (attributes) and methods that operate on that data into a single unit (class). In Python, encapsulation is achieved through the use of private and protected attributes and methods.</p><pre>class BankAccount:<br>    def __init__(self, balance):<br>        self.__balance = balance  # Private attribute<br><br>    def deposit(self, amount):<br>        self.__balance += amount<br><br>    def withdraw(self, amount):<br>        if amount &lt;= self.__balance:<br>            self.__balance -= amount<br>        else:<br>            print(&quot;Insufficient funds.&quot;)<br><br>    def get_balance(self):<br>        return self.__balance<br><br># Create an instance of the BankAccount class<br>account = BankAccount(1000)<br><br># Accessing private attribute (not recommended)<br>print(account._BankAccount__balance)  # Output: 1000<br><br># Calling methods<br>account.deposit(500)<br>print(account.get_balance())  # Output: 1500<br><br>account.withdraw(2000)  # Output: Insufficient funds.</pre><p>In this example, the BankAccount class has a private attribute __balance and methods deposit, withdraw, and get_balance that operate on that attribute. The __balance attribute is private, so it cannot be accessed directly from outside the class. Instead, we use the get_balance method to retrieve the balance.</p><h3>Abstraction:</h3><p>Abstraction is a concept in OOP that focuses on hiding the implementation details of a class and exposing only the necessary information to the outside world. Abstraction can be achieved through the use of abstract classes and abstract methods.</p><pre>from abc import ABC, abstractmethod<br><br>class Shape(ABC):<br>    @abstractmethod<br>    def area(self):<br>        pass<br><br>class Rectangle(Shape):<br>    def __init__(self, width, height):<br>        self.width = width<br>        self.height = height<br><br>    def area(self):<br>        return self.width * self.height<br><br>class Circle(Shape):<br>    def __init__(self, radius):<br>        self.radius = radius<br><br>    def area(self):<br>        return 3.14 * self.radius ** 2<br><br># Create instances of the Rectangle and Circle classes<br>rectangle = Rectangle(5, 10)<br>circle = Circle(5)<br><br># Call the area method on the Rectangle and Circle objects<br>print(rectangle.area())  # Output: 50<br>print(circle.area())     # Output: 78.5</pre><p>In this example, the Shape class is an abstract class with an abstract method area. The Rectangle and Circle classes are subclasses of the Shape class and provide implementations for the area method. The Shape class cannot be instantiated directly, but it serves as a blueprint for creating concrete shapes like rectangles and circles.</p><h3>Conclusion:</h3><p>These are some of the basic concepts of OOP in Python. By using classes and objects, you can create reusable and modular code, which can be easier to maintain and understand. OOP is a powerful paradigm that can help you write more organized and efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c149231d8e1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simulated Color-Tracking Robot with Control System as PID in C++]]></title>
            <link>https://medium.com/@jaiswalnitin054/simulated-color-tracking-robot-f5c2406a9289?source=rss-bf001e77cf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5c2406a9289</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[control-system]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Nitin Bhagat]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 23:51:59 GMT</pubDate>
            <atom:updated>2024-01-14T07:03:40.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>In this project, we will build a simulated robot capable of tracking and following a colored object within a Gazebo environment. The key components include a C++ control system using PID controller, OpenCV for computer vision, a physics engine (Gazebo) for simulating robot movements, and simulated motor control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGiFUEj-4wpne6ybYWEyqQ.png" /><figcaption>Robot model urdf display</figcaption></figure><p>To visualize above run following:<br><em>roslaunch urdf_tutorial display.launch model:=’$(find my_robot_description)/urdf/my_robot.urdf’</em></p><p>This assumes you have a display.launch file that sets up the RViz configuration for your robot. This should open RViz with the robot model and its TF frames.</p><h3>Project Structure</h3><pre>my_robot_project/<br>|-- build/<br>|-- devel/<br>|-- src/<br>|   |-- my_robot_description/<br>|   |   |-- urdf/<br>|   |   |   |-- my_robot.urdf<br>|   |   |-- CMakeLists.txt<br>|   |   |-- package.xml<br>|-- my_robot_gazebo/<br>|   |-- launch/<br>|   |   |-- my_robot_gazebo.launch<br>|   |-- CMakeLists.txt<br>|   |-- package.xml<br>|-- my_robot_control/<br>|   |-- src/<br>|   |   |-- robot_control_node.cpp<br>|   |-- CMakeLists.txt<br>|   |-- package.xml<br>|-- my_robot_color_tracking/<br>|   |-- src/<br>|   |   |-- color_tracking_node.cpp<br>|   |-- CMakeLists.txt<br>|   |-- package.xml<br>|-- README.md</pre><h3>Steps Overview</h3><h3>Step 1: Set Up ROS and Gazebo</h3><h4>Install ROS (Noetic) and Gazebo on your system. Follow the official ROS and Gazebo installation instructions:</h4><ul><li>ROS Installation: ROS Installation Guide</li><li>Gazebo Installation: Gazebo Installation Guide</li></ul><h4>Create a ROS Workspace</h4><pre>mkdir -p ~/catkin_ws/src<br>cd ~/catkin_ws/src<br>catkin_init_workspace<br>cd ..<br>catkin_make<br>source devel/setup.bash</pre><h3>Step 2: Create a Simple Robot Model</h3><h4>Install Necessary ROS Packages</h4><pre>sudo apt-get install ros-noetic-ros-control ros-noetic-ros-controllers</pre><h4>Create a Simple Robot Model</h4><ol><li>Create a new package for your robot model</li></ol><ul><li>cd ~/catkin_ws/src catkin_create_pkg my_robot_description urdf</li><li>Create a simple URDF file for your robot. Replace the content of my_robot_description/urdf/my_robot.urdf with a basic robot description.</li></ul><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;robot name=&quot;my_robot&quot;&gt;<br><br>  &lt;!-- Define the base link --&gt;<br>  &lt;link name=&quot;base_link&quot;&gt;<br>    &lt;visual&gt;<br>      &lt;geometry&gt;<br>        &lt;cylinder length=&quot;0.2&quot; radius=&quot;0.1&quot;/&gt;<br>      &lt;/geometry&gt;<br>      &lt;material name=&quot;blue&quot;&gt;<br>        &lt;color rgba=&quot;0 0 1 1&quot;/&gt;<br>      &lt;/material&gt;<br>    &lt;/visual&gt;<br>  &lt;/link&gt;<br><br>  &lt;!-- Define the left wheel --&gt;<br>  &lt;joint name=&quot;left_wheel_joint&quot; type=&quot;continuous&quot;&gt;<br>    &lt;parent link=&quot;base_link&quot;/&gt;<br>    &lt;child link=&quot;left_wheel_link&quot;/&gt;<br>    &lt;origin xyz=&quot;0.1 0 0.05&quot; rpy=&quot;0 0 0&quot;/&gt;<br>    &lt;axis xyz=&quot;0 0 1&quot;/&gt;<br>    &lt;limit effort=&quot;100.0&quot; velocity=&quot;1.0&quot; lower=&quot;-3.14&quot; upper=&quot;3.14&quot;/&gt;<br>    &lt;dynamics damping=&quot;0.1&quot;/&gt;<br>  &lt;/joint&gt;<br>  &lt;link name=&quot;left_wheel_link&quot;&gt;<br>    &lt;visual&gt;<br>      &lt;geometry&gt;<br>        &lt;cylinder length=&quot;0.05&quot; radius=&quot;0.05&quot;/&gt;<br>      &lt;/geometry&gt;<br>      &lt;material name=&quot;red&quot;&gt;<br>        &lt;color rgba=&quot;1 0 0 1&quot;/&gt;<br>      &lt;/material&gt;<br>    &lt;/visual&gt;<br>  &lt;/link&gt;<br><br>  &lt;!-- Define the right wheel --&gt;<br>  &lt;joint name=&quot;right_wheel_joint&quot; type=&quot;continuous&quot;&gt;<br>    &lt;parent link=&quot;base_link&quot;/&gt;<br>    &lt;child link=&quot;right_wheel_link&quot;/&gt;<br>    &lt;origin xyz=&quot;0.1 0 -0.05&quot; rpy=&quot;0 0 0&quot;/&gt;<br>    &lt;axis xyz=&quot;0 0 1&quot;/&gt;<br>    &lt;limit effort=&quot;100.0&quot; velocity=&quot;1.0&quot; lower=&quot;-3.14&quot; upper=&quot;3.14&quot;/&gt;<br>    &lt;dynamics damping=&quot;0.1&quot;/&gt;<br>  &lt;/joint&gt;<br>  &lt;link name=&quot;right_wheel_link&quot;&gt;<br>    &lt;visual&gt;<br>      &lt;geometry&gt;<br>        &lt;cylinder length=&quot;0.05&quot; radius=&quot;0.05&quot;/&gt;<br>      &lt;/geometry&gt;<br>      &lt;material name=&quot;green&quot;&gt;<br>        &lt;color rgba=&quot;0 1 0 1&quot;/&gt;<br>      &lt;/material&gt;<br>    &lt;/visual&gt;<br>  &lt;/link&gt;<br><br>  &lt;!-- Define a camera link --&gt;<br>  &lt;link name=&quot;camera_link&quot;&gt;<br>    &lt;visual&gt;<br>      &lt;geometry&gt;<br>        &lt;box size=&quot;0.05 0.05 0.05&quot;/&gt;<br>      &lt;/geometry&gt;<br>      &lt;material name=&quot;grey&quot;&gt;<br>        &lt;color rgba=&quot;0.5 0.5 0.5 1&quot;/&gt;<br>      &lt;/material&gt;<br>    &lt;/visual&gt;<br>  &lt;/link&gt;<br>  &lt;joint name=&quot;camera_joint&quot; type=&quot;fixed&quot;&gt;<br>    &lt;parent link=&quot;base_link&quot;/&gt;<br>    &lt;child link=&quot;camera_link&quot;/&gt;<br>    &lt;origin xyz=&quot;0.2 0 0.05&quot; rpy=&quot;0 0 0&quot;/&gt;<br>  &lt;/joint&gt;<br><br>&lt;/robot&gt;</pre><ul><li>Modify the CMakeLists.txt in your my_robot_description package to install the URDF file.</li><li>install(DIRECTORY urdf/ DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/urdf )</li><li>Build your workspace.</li><li>cd ~/catkin_ws catkin_make source devel/setup.bash</li></ul><h3>Step 3: Integrate Gazebo and ROS</h3><h4>Install Gazebo ROS Packages</h4><pre>sudo apt-get install ros-noetic-gazebo-ros-pkgs ros-noetic-gazebo-ros-control</pre><h4>Create a Gazebo Launch File</h4><ol><li>Create a launch file for Gazebo. Create a new package for Gazebo files.</li></ol><ul><li>cd ~/catkin_ws/src catkin_create_pkg my_robot_gazebo</li><li>Create a launch file my_robot_gazebo/launch/my_robot_gazebo.launch.</li><li>&lt;launch&gt; &lt;param name=&quot;robot_description&quot; command=&quot;$(find xacro)/xacro --inorder &#39;$(find my_robot_description)/urdf/my_robot.urdf&#39;&quot;/&gt; &lt;node pkg=&quot;gazebo_ros&quot; type=&quot;spawn_model&quot; name=&quot;spawn_urdf&quot; args=&quot;-urdf -model my_robot -param robot_description&quot; output=&quot;screen&quot;/&gt; &lt;!-- Other Gazebo plugins and configurations can be added here --&gt; &lt;/launch&gt;</li></ul><p>However, we finally add all the nodes to get following launch file:</p><pre>&lt;launch&gt;<br>    &lt;param name=&quot;robot_description&quot; command=&quot;$(find xacro)/xacro --inorder &#39;$(find my_robot_description)/urdf/my_robot.urdf&#39;&quot;/&gt;<br><br>    &lt;!-- Add a Gazebo camera sensor to the robot --&gt;<br>    &lt;node name=&quot;spawn_urdf&quot; pkg=&quot;gazebo_ros&quot; type=&quot;spawn_model&quot; args=&quot;-urdf -model my_robot -param robot_description -J camera_joint&quot;/&gt;<br><br>    &lt;!-- Launch color tracking node --&gt;<br>    &lt;node name=&quot;color_tracking_node&quot; pkg=&quot;my_robot_color_tracking&quot; type=&quot;color_tracking_node&quot; output=&quot;screen&quot;/&gt;<br><br>    &lt;!-- Launch robot control node --&gt;<br>    &lt;node name=&quot;robot_control_node&quot; pkg=&quot;my_robot_control&quot; type=&quot;robot_control_node&quot; output=&quot;screen&quot;/&gt;<br><br>    &lt;!-- Other Gazebo plugins and configurations can be added here --&gt;<br>&lt;/launch&gt;</pre><h3>Step 4: Implement Color Tracking</h3><h3>Modify Gazebo Launch File</h3><p>First, let’s add a Gazebo camera sensor to your robot. Open the my_robot_gazebo/launch/my_robot_gazebo.launch file and add the following lines to include a Gazebo camera sensor:</p><pre>&lt;launch&gt;<br>    &lt;!-- Existing content --&gt;<br>&lt;!-- Add a Gazebo camera sensor to the robot --&gt;<br>    &lt;node name=&quot;spawn_urdf&quot; pkg=&quot;gazebo_ros&quot; type=&quot;spawn_model&quot; args=&quot;-urdf -model my_robot -param robot_description -J camera_joint&quot;/&gt;<br>    <br>    &lt;!-- Other Gazebo plugins and configurations can be added here --&gt;<br>&lt;/launch&gt;</pre><p>Here ‘<strong>camera_joint’</strong> is actual joint name connecting our camera link. This joint name can be found in your URDF file.</p><h3>Create ROS Nodes for Color Tracking</h3><p>Now, let’s create ROS nodes for color tracking. We’ll create a new package, for example, my_robot_color_tracking. You can do this using the following commands:</p><pre>cd ~/catkin_ws/src<br>catkin_create_pkg my_robot_color_tracking rospy sensor_msgs cv_bridge</pre><p>This creates a new package with dependencies on rospy (ROS Python library), sensor_msgs (ROS messages for sensor data), and cv_bridge (ROS OpenCV bridge).</p><h4>Create Color Tracking Node</h4><p>Create a C++ script in the my_robot_color_tracking/src directory, for example,color_tracking_node.cpp</p><pre>#include &lt;ros/ros.h&gt;<br>#include &lt;sensor_msgs/Image.h&gt;<br>#include &lt;cv_bridge/cv_bridge.h&gt;<br>#include &lt;opencv2/opencv.hpp&gt;<br><br>class ColorTrackingNode<br>{<br>public:<br>    ColorTrackingNode() : nh_()<br>    {<br>        image_sub_ = nh_.subscribe(&quot;/my_robot/camera_link/camera/image&quot;, 1, &amp;ColorTrackingNode::imageCallback, this);<br>    }<br><br>    void imageCallback(const sensor_msgs::Image::ConstPtr&amp; msg)<br>    {<br>        try<br>        {<br>            cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);<br>            cv::Mat cv_image = cv_ptr-&gt;image;<br><br>            // Perform color tracking logic here<br>            // Example: Detect a red color<br>            cv::Mat mask;<br>            cv::inRange(cv_image, cv::Scalar(0, 0, 100), cv::Scalar(100, 100, 255), mask);<br><br>            // Process the tracked object<br>            // Replace this with your actual tracking logic<br><br>            // Show the result (for debugging)<br>            cv::imshow(&quot;Color Tracking&quot;, cv_image);<br>            cv::waitKey(1);<br>        }<br>        catch (cv_bridge::Exception&amp; e)<br>        {<br>            ROS_ERROR(&quot;Error processing image: %s&quot;, e.what());<br>        }<br>    }<br><br>private:<br>    ros::NodeHandle nh_;<br>    ros::Subscriber image_sub_;<br>};<br><br>int main(int argc, char** argv)<br>{<br>    ros::init(argc, argv, &quot;color_tracking_node&quot;);<br>    ColorTrackingNode color_tracking_node;<br><br>    ros::spin();<br>    return 0;<br>}</pre><p>Make sure to add the necessary dependencies in your my_robot_color_tracking package&#39;s CMakeLists.txt:</p><pre>find_package(catkin REQUIRED COMPONENTS<br>  rospy<br>  sensor_msgs<br>  cv_bridge<br>)<br>catkin_package()<br>include_directories(<br>  ${catkin_INCLUDE_DIRS}<br>)<br>add_executable(color_tracking_node src/color_tracking_node.cpp)<br>target_link_libraries(color_tracking_node ${catkin_LIBRARIES})</pre><p>NOTE: so basically in CMakelists.txt for all nodes we create we update/add</p><p><em>add_executable</em> and <em>target_link_libraries.</em></p><p>After making these changes, rebuild your workspace:</p><pre>cd ~/catkin_ws<br>catkin_make</pre><p>Now, you should be able to run the simulation with the updated C++ color tracking node.</p><h4>Gazebo and ROS Integration</h4><p>Detail the modifications made to the Gazebo launch file to include the color tracking and robot control nodes.</p><pre>&lt;!-- Modified Gazebo launch file snippet --&gt;<br>&lt;launch&gt;<br>  &lt;!-- ... --&gt;<br>  &lt;node name=&quot;color_tracking_node&quot; pkg=&quot;my_robot_color_tracking&quot; type=&quot;color_tracking_node&quot; output=&quot;screen&quot;/&gt;<br>  &lt;node name=&quot;robot_control_node&quot; pkg=&quot;my_robot_control&quot; type=&quot;robot_control_node&quot; output=&quot;screen&quot;/&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/launch&gt;</pre><h3>Step 5: Implement Simulated Robot Control</h3><h4>Create a Simple Controller</h4><ol><li>Create a new package for controllers.</li></ol><ul><li>cd ~/catkin_ws/src catkin_create_pkg my_robot_control</li><li>Create a simple controller file my_robot_control/config/my_robot_control.yaml.</li><li>my_robot: type: joint_state_controller/JointStateController</li></ul><h4>Step 6: Final Integration</h4><p>Add the following lines to the Gazebo launch file to load the controller.</p><pre>&lt;node name=&quot;controller_spawner&quot; pkg=&quot;controller_manager&quot; type=&quot;spawner&quot; respawn=&quot;false&quot;<br>    output=&quot;screen&quot; ns=&quot;/my_robot&quot; args=&quot;my_robot joint_state_controller&quot;/&gt;</pre><h3>Step 6: Final Integration</h3><h4>Modify the Gazebo Launch File</h4><p>Add the following lines to the Gazebo launch file to integrate the robot control with Gazebo.</p><pre>&lt;node name=&quot;robot_state_publisher&quot; pkg=&quot;robot_state_publisher&quot; type=&quot;robot_state_publisher&quot; respawn=&quot;false&quot; output=&quot;screen&quot;&gt;<br>    &lt;param name=&quot;publish_frequency&quot; type=&quot;double&quot; value=&quot;50.0&quot;/&gt;<br>    &lt;param name=&quot;tf_prefix&quot; type=&quot;string&quot; value=&quot;my_robot&quot;/&gt;<br>&lt;/node&gt;<br></pre><p>This is how the final gazebo launch file will look like:</p><pre>&lt;launch&gt;<br>    &lt;param name=&quot;robot_description&quot; command=&quot;$(find xacro)/xacro --inorder &#39;$(find my_robot_description)/urdf/my_robot.urdf&#39;&quot;/&gt;<br><br>    &lt;!-- &lt;node pkg=&quot;gazebo_ros&quot; type=&quot;spawn_model&quot; name=&quot;spawn_urdf&quot; args=&quot;-urdf -model my_robot -param robot_description&quot; output=&quot;screen&quot;/&gt; --&gt;<br><br> &lt;!-- Add a Gazebo camera sensor to the robot --&gt;<br>    &lt;node name=&quot;spawn_urdf&quot; pkg=&quot;gazebo_ros&quot; type=&quot;spawn_model&quot; args=&quot;-urdf -model my_robot -param robot_description -J camera_joint&quot;/&gt;<br>    <br>&lt;!-- Launch color tracking node --&gt;<br>&lt;node name=&quot;color_tracking_node&quot; pkg=&quot;my_robot_color_tracking&quot; type=&quot;color_tracking_node&quot; output=&quot;screen&quot;/&gt;<br><br><br>&lt;!-- Launch robot control node --&gt;<br>&lt;node name=&quot;robot_control_node&quot; pkg=&quot;my_robot_control&quot; type=&quot;robot_control_node&quot; output=&quot;screen&quot;/&gt;<br><br>    &lt;!-- Other Gazebo plugins and configurations can be added here --&gt;<br>&lt;/launch&gt;</pre><h3>Step 7: Run the Simulation</h3><pre>roslaunch my_robot_gazebo my_robot_gazebo.launch</pre><h3>Conclusion</h3><p>By following these steps and utilizing the provided project structure, you’ll have a fully functional simulated robot capable of color tracking and following within a Gazebo environment. This project serves as a robust foundation for experimenting with various control strategies and enhancements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c2406a9289" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>