<?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 Hemanthhari2000 on Medium]]></title>
        <description><![CDATA[Stories by Hemanthhari2000 on Medium]]></description>
        <link>https://medium.com/@hemanthhari2000?source=rss-c4e35395b2b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-zlZdPcvZONHBwbT</url>
            <title>Stories by Hemanthhari2000 on Medium</title>
            <link>https://medium.com/@hemanthhari2000?source=rss-c4e35395b2b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:35:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hemanthhari2000/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[The Ports and Adapters Pattern: Unraveling the Mystery]]></title>
            <link>https://hemanthhari2000.medium.com/the-ports-and-adapters-pattern-unraveling-the-mystery-2efbf678ab9b?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2efbf678ab9b</guid>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 13:11:17 GMT</pubDate>
            <atom:updated>2024-11-26T10:47:18.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Dive deep into the ports and adapters pattern to grasp its crucial role in creating resilient, robust and modular software architecture in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHsBW7JwHNQJkqB8DThypA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">CHUTTERSNAP</a> on <a href="https://unsplash.com/photos/worms-eye-view-of-white-concrete-building-mf-o1E7omzk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Designing and maintaining a resilient software architecture can be quite challenging, specifically in systems that need high adaptability and long-term robustness. One of the common concerns while working with such an architecture is managing dependencies and ensuring that changes made in one part of the system do not affect the entire application. This is where the ports and adapters pattern, also known as the hexagonal architecture, steps in to expedite the process.</p><p>The ports and adapters pattern is a subset of SOLID principles that decouples a system’s core logic from its external dependencies, such as databases and other services. This pattern helps to build applications that are modular, maintainable, and testable, making them scalable. By separating the domain or core business logic from external resources, this pattern ensures that the system remains flexible and resilient to changes within the domain. In this article, we will delve into the concepts of ports and adapters and implement them in the Python programming language using FastAPI framework.</p><h3>Overview</h3><p>Let’s take a look at the topics that we are going to cover in this article.</p><ul><li>What is the ports and adapters pattern?</li><li>Why choose the ports and adapters pattern?</li><li>What are we building?</li><li>Prerequisites</li><li>Implementation</li><li>Conclusion</li><li>References</li></ul><h3>What is the ports and adapters pattern?</h3><p>The ports and adapters pattern, or hexagonal architecture, is an architectural pattern used in software design. It aims at creating loosely coupled application components that can be easily connected to their software environment by means of ports and adapters. Ports represent the system’s entry points, and adapters handle external systems like databases and third-party services. By setting such boundaries, the domain or core logic remains isolated and agnostic of the surrounding infrastructure, making it easier to test, maintain, and scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSW-bsk-O8oJhldK88Gumw.png" /><figcaption>Hexagonal Architecture</figcaption></figure><p>At a foundational level, this pattern inspires a design where the core application is surrounded by a layer of interfaces (which are nothing but ports) that define the operations available to the outside world. These interfaces, or ports, are then connected to external resources through adapters. The adapters are nothing but mere implementations of interfaces or ports. For example, a database adapter would handle the data retrieval and storage operations, translating them into a form the core application could understand and use. Such partitioning between external resources and domains allows developers to edit or replace adapters without touching the core logic. This helps promote flexibility and resilience in the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*nLNGZ52BoT58uN5v1gQHvA.png" /><figcaption>Architecture flow</figcaption></figure><p>One of the biggest benefits of this pattern is its ability to enhance the testability and maintainability of software. Because of the isolation of business logic and external dependencies, developers can write unit tests that solely focus on the core functionality. This enables the application to quickly adapt to new technologies, as changes to external systems only require certain updates to the respective adapters, leaving the core domain logic intact. The bottom line is that this pattern provides a robust framework for building software that is both adaptable to change and cloistered from the complexities of its environment.</p><h3>Why choose the ports and adapters pattern?</h3><p>Adopting this pattern offers several compelling advantages for modern software development. One of its primary benefits is the clear separation between the core business logic and external dependencies. This separation ensures that the core logic remains clean, focused, and devoid of infrastructure concerns like database, service, and user interface integrations. As a result, the core logic becomes easier to understand, develop, and test in isolated environments. By decoupling the application from third-party services, the application becomes inherently more maintainable. Developers can evolve the business functionality without worrying about breaking changes in the system’s external interfaces, thus supporting agile and iterative development practices.</p><p>Moreover, this pattern significantly enhances the flexibility and resilience of the application. By isolating the core from the specifics of external systems, it becomes straightforward to swap out or upgrade these external resources. For instance, if an application switches from one database to another or integrates with a new service provider, you only need to change or replace the respective adapter. The core business logic remains intact. This modularity allows organisations to adapt quickly to changing technological landscapes and business requirements, reducing the risk and effort associated with system upgrades or migrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amVNpQS6zMNTFeYrk7FFVA.png" /><figcaption>Data flow with the architecture</figcaption></figure><p>While this pattern offers significant benefits, it does come with some notable drawbacks. One major challenge is the increased complexity it introduces to the codebase. Each additional line of code is a liability that requires constant maintenance. Furthermore, the pattern’s steep learning curve can be a barrier for new programmers, requiring substantial time and effort to understand and effectively implement it in projects.</p><h3>What are we building?</h3><p>In this tutorial, we will build a Todo application using Python and the FastAPI framework. Our application will use SQLite3 as its database, and Alembic for handling data migrations. We’ll start from scratch by setting up a new FastAPI project and continue to develop it into a fully functional Todo app capable of performing Create, Read, Update, and Delete (CRUD) operations with the database.</p><h3>Prerequisites</h3><p>Following are the prerequisites before we start building our Todo application.</p><ul><li>Python (^3.10)</li><li>Poetry (Python packaging tool) (latest version recommended)</li><li>FastAPI (^0.111.0)</li><li>Sqlalchemy (^2.0.30)</li><li>Alembic (^1.13.1)</li><li>Pydantic (^2.7.3)</li></ul><h3>Implementation</h3><p>Let’s get started with our implementation. All the resources are added at the end of this article for your reference.</p><h4>Project setup</h4><p>First let’s create a new python project using Poetry tool. Follow the below command to create a new python project named todo_app. Don’t worry about the --name flag as it creates a new module inside src called entrypoints</p><pre>poetry new todo_app --src --name entrypoints</pre><p>Now, let’s create some more modules inside our src folder namely, adapters and domain. Create a main.py file that will act as our main file for the whole application.</p><p>Now, its time for installing the required packages for our project. Run the following command that will install the packages.</p><pre>poetry add fastapi sqlalchemy alembic pydantic</pre><p><strong><em>Note: Please note that Poetry will install Python by default and it is not required to add it separately.</em></strong></p><h4>Alembic setup</h4><p>Let’s setup alembic in our project as our database migration tool. First run the following command to confirm alembic is installed properly.</p><pre>poetry run alembic --version</pre><p>If you see the alembic version then you are good to go. Else, please properly install the package. Moving on, let’s configure alembic to our project using the following command</p><pre>poetry run alembic init alembic</pre><p>The above command initialises alembic by creating alembic/ folder and a config file called alembic.ini. There are few changes that we have to do inside alembic.ini file. Replace the following line</p><pre>- # sqlalchemy.url = driver://user:pass@localhost/dbname<br>+ sqlalchemy.url = sqlite:///./todos_app.db</pre><p>Now, we are all set to create our first migration. In order to create a migration in alembic you have to create a revision. This is an alembic revision that keeps track of the migrations. So let’s create our revision using the following command.</p><pre>poetry run alembic revision -m &quot;initial revision&quot;</pre><p>This will create a new revision in alembic/versions/XX_initial_revision.py file. You can see it created a new Python file with upgrade() and downgrade() functions in it. It is our job to define the migration logic for both upstream and downstream changes. The upgrade() function applies the migration and the downgrade() function removes/reverts the migration. That’s all. Now populate both the methods using the following in alembic/versions/XX_initial_revision.py file.</p><pre>from typing import Sequence, Union<br>import sqlalchemy as sa<br>from alembic import op<br><br>def upgrade() -&gt; None:<br>    op.create_table(<br>        &quot;todos&quot;,<br>        sa.Column(&quot;id&quot;, sa.Text(), nullable=False),<br>        sa.Column(&quot;title&quot;, sa.String(), nullable=False),<br>        sa.Column(&quot;description&quot;, sa.String(), nullable=True),<br>        sa.Column(&quot;priority&quot;, sa.Integer(), nullable=True),<br>        sa.Column(&quot;is_completed&quot;, sa.Boolean(), nullable=False),<br>        sa.PrimaryKeyConstraint(&quot;id&quot;),<br>    )<br>    op.create_index(op.f(&quot;ix_todo_id&quot;), &quot;todos&quot;, [&quot;id&quot;], unique=False)<br><br>def downgrade() -&gt; None:<br>    op.drop_index(op.f(&quot;ix_todo_id&quot;), table_name=&quot;todos&quot;)<br>    op.drop_table(&quot;todos&quot;)</pre><p>Let’s go ahead and apply the migration using this command</p><pre>poetry run alembic upgrade head</pre><p>That’s it. We are done with our alembic setup and we have successfully applied the migrations as well. This should have created todos_app.db file in the root folder of your project which will have an empty table called todos with the above mentioned columns. Finally, after all the initial setup the folder structure should look something like this</p><pre>todo_app<br>├── README.md<br>├── alembic<br>├── alembic.ini<br>├── poetry.lock<br>├── pyproject.toml<br>├── src<br>│   ├── adapters/<br>│   ├── domain/<br>│   └── entrypoints/<br>│   └── main.py<br>└── tests<br>    └── __init__.py</pre><p><strong><em>Note: The detailed code structure can be found in this </em></strong><a href="https://github.com/Hemanthhari2000/todo-app-ports-and-adapters"><strong><em>Github Repository</em></strong></a></p><p>Let’s look at each of the files and folder created by Poetry</p><ul><li>todo_app/: The root folder of our Poetry project.</li><li>README.md: The Readme file of our project where you can add the projects description and more.</li><li>alembic/: Alembic folder containing all of our migration revision code.</li><li>alembic.ini: Alembic configuration file that is used to define database url, creating a template for the revision files and so on.</li><li>poetry.lock: Its a file that keeps track of all the exact versions of the dependencies used in a project, including the hashes of their source files</li><li>pyproject.toml: It is a configuration file used by Poetry to define the project’s metadata and configuration. It is similar to the package.json file used in Node.js.</li><li>src/: The source folder of our project where all the logic including ports and adapters reside.</li><li>adapters/: The folder where all of our adapter code is present.</li><li>domain/: The folder where all the domain logic is present.</li><li>entrypoints/: The folder where all FastAPI routes or endpoints reside.</li><li>main.py: This file acts as our main file for the whole application.</li><li>tests/: It will contain all the test cases for the application. <strong>This is out of scope for this article and we will not be writing any test cases for this application.</strong></li></ul><p>Now, that we have setup the project and installed the required packages, let’s build our first entrypoint. Add the following code in src/entrypoints/api/todo/router.py</p><pre>from fastapi import APIRouter<br><br>router = APIRouter()<br><br>@router.get(&quot;/&quot;)<br>def get_all_todo(): <br>  return {&quot;message&quot;: &quot;hello&quot;}</pre><p>Now, configure this particular route in src/entrypoints/api/router.py like this</p><pre>from fastapi import APIRouter<br>from .todo import router as todo<br><br>router = APIRouter(prefix=&#39;/v1&#39;)<br><br>router.include_router(todo.router, prefix=&#39;/todo&#39;, tags=[&#39;todo&#39;])</pre><p>Here, we have configured the get_all_todo() endpoint. Let’s create a FastAPI instance and connect our application router to it in src/entrypoints/api/main.py</p><pre>from fastapi import FastAPI<br>from .router import router<br><br>app = FastAPI()<br><br>app.include_router(router=router)</pre><p>Now that we have added our entrypoint or route to the FastAPI instance, let’s start the FastAPI application in src/main.py file.</p><pre>import uvicorn<br>from entrypoints.api.main import app<br><br>uvicorn.run(&quot;entrypoints.api.main:app&quot;, host=&quot;0.0.0.0&quot;, port=8000, reload=True)</pre><p>That’s it, we are done with the FastAPI setup. We can now run the following command to run the FastAPI application on port 8000. The swaggers documentation can be accessed here <a href="http://localhost:8000/docs">http://localhost:8000/docs</a></p><pre>poetry run python src/main.py</pre><p>Now that we are done with the FastAPI setup and also configured a route, let’s start with defining our Ports. But before that, we need to define our database table. So, add the following in src/adapters/db/schema.py file.</p><pre>from sqlalchemy import (<br>    Boolean,<br>    Column,<br>    Integer,<br>    String,<br>    Text,<br>)<br>from contextlib import contextmanager<br>from sqlalchemy import create_engine<br>from sqlalchemy.orm import (<br>    declarative_base,<br>    sessionmaker,<br>)<br><br>SQLALCHEMY_DATABASE_URL = &quot;sqlite:///./todos_app.db&quot;<br>Base = declarative_base()<br><br>class DBSession:<br>    def __init__(self) -&gt; None:<br>        self.engine = create_engine(<br>            SQLALCHEMY_DATABASE_URL, connect_args={&quot;check_same_thread&quot;: False}<br>        )<br>        self.Session = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)<br><br>    @contextmanager<br>    def get_db(self):<br>        session = self.Session()<br>        try:<br>            yield session<br>        finally:<br>            session.close()<br><br><br>class TodoTable(Base):<br>    __tablename__ = &quot;todos&quot;<br><br>    id = Column(Text, primary_key=True, index=True)<br>    title = Column(String)<br>    description = Column(String)<br>    priority = Column(Integer)<br>    is_completed = Column(Boolean, default=False)</pre><p>For simplicity sake, I am adding the database session class in the same file. If you want you can create a new file called session.py and add all the session related code there. Anyhow, we are done with table creation part. Let’s begin defining our Ports. So in src/domain/ports/todo.py file, add the following</p><pre># TodoPort <br># path: src/domain/ports/todo.py<br>from typing import List, Protocol<br><br>from adapters.db.schema import TodoTable<br><br>class TodoPort(Protocol):<br><br>    def create(self, todo: TodoTable) -&gt; None:<br>        &quot;&quot;&quot;Create a new todo&quot;&quot;&quot;<br><br>    def get_all(self) -&gt; List[TodoTable]:<br>        &quot;&quot;&quot;Get list of all todos&quot;&quot;&quot;<br><br>    def get_todo_by_id(self, todo_id: str) -&gt; TodoTable:<br>        &quot;&quot;&quot;Get todo by unique todo id&quot;&quot;&quot;<br><br>    def update(self, todo: TodoTable) -&gt; None:<br>        &quot;&quot;&quot;Update existing todo with updated values&quot;&quot;&quot;<br><br>    def delete_todo_by_id(self, todo_id: str) -&gt; None:<br>        &quot;&quot;&quot;Delete a single existing todo with todo Id&quot;&quot;&quot;</pre><p><strong><em>Note: We are adding our ports under domain folder. This is a common practice since ports only define an interface and do not include implementation logic. Anything that implements ports will go under adapters folder.</em></strong></p><p>From the above it should be pretty clear that we have defined our ports which means we have exposed our application to connect to adapters through these ports. Let’s implement these ports in src/adapters/todo_adapter.py file</p><pre># TodoAdapter <br># path: src/adapters/todo_adapter.py<br>from typing import List<br><br>from adapters.db.schema import TodoTable, DBSession<br>from domain.ports.todo import TodoPort<br><br>class TodoAdapter(TodoPort):<br>    def __init__(self) -&gt; None:<br>        self.db_session = DBSession()<br><br>    def create(self, todo: TodoTable) -&gt; None:<br>        with self.db_session.get_db() as db:<br>            db.add(todo)<br>            db.commit()<br><br>    def get_all(self) -&gt; List[TodoTable]:<br>        with self.db_session.get_db() as db:<br>            return db.query(TodoTable).all()<br><br>    def get_todo_by_id(self, todo_id: str) -&gt; TodoTable:<br>        with self.db_session.get_db() as db:<br>            return db.query(TodoTable).filter(TodoTable.id == todo_id).one_or_none()<br><br>    def update(self, todo: TodoTable) -&gt; None:<br>        with self.db_session.get_db() as db:<br>            todo_to_update = self.get_todo_by_id(todo_id=str(todo.id))<br>            if todo_to_update is None:<br>                raise ValueError(&quot;Error: Item not found&quot;)<br><br>            todo_to_update.title = todo.title<br>            todo_to_update.description = todo.description<br>            todo_to_update.priority = todo.priority<br>            todo_to_update.is_completed = todo.is_completed<br><br>            db.add(todo_to_update)<br>            db.commit()<br><br>    def delete_todo_by_id(self, todo_id: str) -&gt; None:<br>        with self.db_session.get_db() as db:<br>            todo = self.get_todo_by_id(todo_id=todo_id)<br>            db.delete(todo)<br>            db.commit()</pre><p>As you can see, we are only implementing the ports that we defined previously. This is a common database CRUD operation code where we interact with sql database through Sqlalchemy ORM.</p><p>Let’s summarise what we have done so far. We have created an API endpoint and configured our FastAPI application to it. Next, we have defined our database port that exposes certain functions to adapters. Finally, we have implemented those ports in our database adapters code.</p><p>Now, let’s go a bit further and connect our FastAPI endpoint and the database adapter so that we get a single flow of data from FastAPI to database. You can directly connect them or you could use another layer called service layer to interact with endpoints and database adapter layer. This is again a common practice to decouple our codebase. Let’s create a service called TodoService in src/domain/todo/service.py where most of our domain logic goes.</p><pre># TodoService<br># path: src/domain/todo/service.py<br>from typing import List<br>from adapters.db.schema import TodoTable<br>from domain.ports.todo import TodoPort<br>from domain.todo.model import TodoModel<br><br>class TodoService:<br>    def __init__(self, todo_port: TodoPort) -&gt; None:<br>        self.todo_adapter = todo_port<br><br>    def create(self, todo: TodoModel) -&gt; None:<br>        todo = TodoTable(**todo.model_dump())<br>        self.todo_adapter.create(todo=todo)<br><br>    def get_all(self) -&gt; List[TodoModel]:<br>        todos = self.todo_adapter.get_all()<br>        return TodoModel.from_db_model(todos)<br><br>    def get_todo_by_id(self, todo_id: str) -&gt; TodoModel:<br>        todo_by_id = self.todo_adapter.get_todo_by_id(todo_id=todo_id)<br>        return TodoModel.from_db_model(todo_by_id)<br><br>    def update(self, todo: TodoModel) -&gt; None:<br>        self.todo_adapter.update(todo=TodoTable(**todo.model_dump()))<br><br>    def delete_todo_by_id(self, todo_id: str) -&gt; None:<br>        self.todo_adapter.delete_todo_by_id(todo_id=todo_id)</pre><p>If you notice here we are importing TodoModel which we have not created yet. TodoModel is a Pydantic model that validates the data that comes from request body of endpoints. Let’s quickly look at how it is defined in src/domain/todo/model.py</p><pre># path: src/domain/todo/model.py<br>from typing import List<br>from pydantic import BaseModel, ConfigDict<br>from adapters.db.schema import TodoTable<br><br>class TodoModel(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br><br>    id: str = &quot;&quot;<br>    title: str<br>    description: str = &quot;&quot;<br>    priority: int<br>    is_completed: bool<br><br>    @staticmethod<br>    def from_db_model(todo: TodoTable | List[TodoTable]):<br>        if isinstance(todo, TodoTable):<br>            return TodoModel.model_validate(todo)<br>        return [TodoModel.model_validate(t) for t in todo]</pre><p>You can add a bunch of validations to your data, but for this example I am sticking with these. Feel free to add your own validations and customise it as you like.</p><p>Now that we have our service layer that connects the gap between our endpoints and database adapter, all we have to do now is to connect the service with our endpoints so that the data from endpoint will pass through our service layer and then interact with our database adapter and return the required data back to us. With this, our flow should be complete.</p><p>Update the following route in src/entrypoints/api/todo/router.py by adding service object and calling the adapters through our service layer.</p><pre># path: src/entrypoints/api/todo/router.py<br>import uuid<br>from fastapi import APIRouter, Depends<br>from adapters.todo_adapter import TodoAdapter<br>from domain.todo.model import TodoModel<br>from domain.todo.service import TodoService<br><br>router = APIRouter()<br><br>def get_todo_service() -&gt; TodoService:<br>    todo_adapter = TodoAdapter()<br>    return TodoService(todo_port=todo_adapter)<br><br>@router.get(&quot;/&quot;)<br>def get_all_todo(service: TodoService = Depends(get_todo_service)):<br>    return service.get_all()<br><br>@router.get(&quot;/{id}&quot;)<br>def get_todo_by_id(id: str, service: TodoService = Depends(get_todo_service)):<br>    return service.get_todo_by_id(todo_id=id)<br><br>@router.post(&quot;/create&quot;)<br>def create_todo(todo_model: TodoCreateModel, service: TodoService = Depends(get_todo_service)):<br>    todo_id = str(uuid.uuid4())<br>    service.create(todo=TodoModel(**todo_model.model_dump(), id=todo_id))<br>    return {f&quot;Todo Created with id: {todo_id}&quot;}<br><br>@router.put(&quot;/update&quot;)<br>def update_todo(todo_model: TodoModel, service: TodoService = Depends(get_todo_service)):<br>    service.update(todo=todo_model)<br>    return {f&quot;Todo Updated, id: {todo_model.id}&quot;}<br><br>@router.delete(&quot;/delete/{id}&quot;)<br>def delete_todo_by_id(_id: str, service: TodoService = Depends(get_todo_service)):<br>    service.delete_todo_by_id(todo_id=_id)<br>    return {f&quot;Todo Deleted, id: {_id}&quot;}</pre><p>Alright, now we have everything we need. We have our FastAPI routes declared, a service layer that passes data to the next layer, ports, or interfaces where we have declared specific functions through which the adapters can connect, and finally the adapters themselves, which perform the data operations. If you observe closely, our core logic in the service layer doesn’t concern itself with the next layer. It doesn’t even know it’s passing data to an adapter. Its role is simply to call functions declared in the ports. That’s the power of this pattern: the core logic remains unaware of the adapters. For example, in this case, it doesn’t matter whether you’re using a database or a REST API handler. The core logic will invoke the functions defined in the ports. However, it’s crucial that the adapters are properly configured with the ports.</p><p>Now try running this command and see the magic unfold.</p><pre>poetry run python src/main.py</pre><p>The above command should run the FastAPI application and You can find the swaggers documentation at this url <a href="http://localhost:8000/docs">http://localhost:8000/docs</a>. Your output should look something similar to this.</p><p><strong><em>Note: The output might vary because I’ve added a couple of new endpoints other than the ones discussed in this article. Please feel free to modify as you like.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PR0vRAsoiUVnMygP2cZSxA.png" /><figcaption>FastAPI Swaggers documentation</figcaption></figure><h3>Conclusion</h3><p>In this article, we explored the ports and adapters pattern, discussing its advantages and potential drawbacks. We also walked through building a Todo application from scratch using FastAPI, and configured Alembic for database migrations. During this process, we created new ports, implemented their corresponding adapters, and connected them through the service layer. This pattern effectively decouples the core logic from external dependencies, allowing us to concentrate on development and scalability. I hope you found this article helpful. I will see you in my next article. Until then, as always <strong>code learn repeat ……..</strong></p><h3>References</h3><ul><li><a href="https://github.com/Hemanthhari2000/todo-app-ports-and-adapters"><strong>Github Repository</strong></a></li><li><a href="https://alembic.sqlalchemy.org/en/latest/tutorial.html#running-our-first-migration"><strong>Alembic First Migration Doc</strong></a></li><li><a href="https://docs.pydantic.dev/latest/api/base_model/"><strong>Pydantic Documentation</strong></a></li><li><a href="https://douwevandermeij.medium.com/hexagonal-architecture-in-python-7468c2606b63"><strong>Hexagonal Architecture in Python by Douwe van der Meij</strong></a></li><li><a href="https://medium.com/ssense-tech/hexagonal-architecture-there-are-always-two-sides-to-every-story-bc0780ed7d9c"><strong>Hexagonal Architecture, there are always two sides to every story</strong></a></li></ul><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2efbf678ab9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolving Security Vulnerabilities using Snyk]]></title>
            <link>https://hemanthhari2000.medium.com/resolving-security-vulnerabilities-using-snyk-20e393a4efff?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/20e393a4efff</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[snyk]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 17:21:38 GMT</pubDate>
            <atom:updated>2023-11-02T17:21:38.678Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to track, resolve and automatically fix security vulnerabilities in your code and containers using Snyk tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qF1J5KVauC-KmfZzQBTy7w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@speedoshots?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Miłosz Klinowski</a> on <a href="https://unsplash.com/photos/two-grey-cctv-cameras-BW0d0IllW8E?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In the ever-evolving landscape of software development, security has emerged as a paramount concern. With cyber threats becoming increasingly sophisticated and frequent, organizations can no longer afford to treat security as an afterthought. Let me introduce Snyk, an innovative tool that has created quite the uproar in the DevSecOps domain. This blog will guide you on an informative journey to discover how Snyk is different when it comes to software security by enabling developers and organisations to create and manage secure code from the ground up.</p><p>Snyk has redefined how organisations address security concerns by shifting the focus from reactive measures to proactive prevention. It integrates seamlessly into the development workflow, enabling developers to find, fix, and prevent security vulnerabilities in real-time, long before they pose a threat. This method saves time, labour, and resources by streamlining the development process and enhancing security. Snyk offers perfect balance between speed and security in a time when both are essential, enabling project teams to develop quickly without sacrificing security. Let’s go into greater detail about Snyk in the paragraphs that follow, going over its key characteristics, advantages, and how it’s changing the way we build and deploy code.</p><h3>Overview</h3><p>Let’s look at topics covered in this article.</p><ul><li>What is Snyk?</li><li>How to use Snyk?</li><li>Information present in Snyk</li><li>Snyk CLI Commands</li><li>Conclusion</li></ul><h4>What is Snyk?</h4><p>Snyk is a simple platform that allows you to scan, identify and fix security vulnerabilities in your code, container images, open source dependencies and infrastructure as code configurations. It is a powerful and versatile tool that plays a pivotal role in enhancing the security and reliability of software applications. It is a developer centric platform focussed to identify and fixing vulnerabilities in the early stage of the software development lifecycle. Personally, I’ve used Snyk quite extensively in my projects and it has been really amazing experience and it stands out because of its effectiveness in finding and mitigating security issues proactively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*JdjDG3RFLDC-VC4YCLI4-g.png" /></figure><p>Fundamentally, Snyk gives developers the tools they need to check for known security flaws in their code, dependencies, and containers. It has an extensive database of vulnerabilities and integrates seamlessly into the development workflow, making it easy to identify and fix issues right from the code editor, CI/CD process and also build pipelines. What distinguishes Snyk is its capacity to identify vulnerabilities and provide not only with useful information about how to address them but also with suggestions for upgrading or applying patches to libraries and packages that are at risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saUa7KKNVGQ3pI56inMEeg.png" /></figure><p>Snyk also excels at supporting a wide range of programming languages, such as JavaScript, Java, Python, and more, which makes it a flexible option for a variety of development stacks. Because of its ongoing monitoring features, developers are always aware of emerging vulnerabilities and can take preventative measures to avoid security issues. In my opinion, Snyk, has proven to be an invaluable resource for protecting apps and making sure they adhere to the toughest security guidelines all during the course of their development.</p><h4>How to use Snyk?</h4><p>Firstly, create an account in Snyk if not already. You can login to Snyk official website and get started for free. Once you are logged in you will be redirected to setup page. You can select your Integration method, install snyk cli tool (highly recommended), authenticate your dev machine and finally scan for any issues. You can also skip this step for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8osyPwUeCplm1wtO9kiDg.png" /><figcaption>Setting up Snyk</figcaption></figure><p>Once the setup is done, then add your projects based on your configuration, that is, if you have integrated with Github then you can add any repository as a project. This will show up in the projects tab in Snyk home page. Once the project is added then you will see the available vulnerabilities based on its critical level, that is, critical, high, medium or low. Most of the things about solving the vulnerability is self explanatory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3TyeXyeokP6FMHmzUrrAg.png" /><figcaption>Projects tab of Snyk</figcaption></figure><h4>Information present in Snyk</h4><p>Once the code is scanned, Snyk provides us with lot of informations. They are as follows:</p><ol><li>Priority of the vulnerability :- the priority can be critical, high, medium or low.</li><li>Introduced through :- tells which dependency caused the vulnerability. It also specifies the nested dependency list in which the vulnerability is introduced.</li><li><a href="https://www.first.org/cvss/">CVSS</a> :- Common Vulnerability Scoring System’s purpose is to identify, define, and catalog publicly disclosed cybersecurity vulnerabilities</li><li><a href="https://cwe.mitre.org/index.html">CWE</a> :- Common Weakness Enumeration is a community-developed list of software and hardware weakness types. It serves as a common language, a measuring stick for security tools, and as a baseline for weakness identification, mitigation, and prevention efforts.</li><li><a href="https://security.snyk.io/vuln/">Snyk vulnerability database</a> has the list of security vulnerabilities.</li></ol><p>Snyk scans all the projects every 24 hours. Snyk also has retest option that helps to trigger the scan whenever needed. Typically used when the vulnerability is fixed.</p><p><strong>Snyk auto fix feature</strong></p><p>Snyk provides options to automatically fix the issues if the issue is related to any package. The fix is not reliable because fixing or updating package version may require code level changes. For this, you still have to manually check with your local changes and then once the changes are passing successfully then only merge the changes. The auto PR fix can be reliable for minor changes in the package.</p><p><strong>Ignore a vulnerability</strong></p><p>Snyk also gives us the option to skip or ignore certain vulnerability. Even though it is not recommended to skip or ignore certain vulnerability but for some edge cases like if the vulnerability is present in another core package, then it is acceptable, or else it is always recommended to fix the vulnerability.</p><p>If you wish to ignore the vulnerability then there are three options that are mentioned as follows:</p><ul><li><strong>Ignore Permanently </strong>:<strong>-</strong> Ignored permanently and it won’t appear in the dashboard</li><li><strong>Ignore temporarily </strong>:- Ignored temporarily for a period of time.</li><li><strong>Not vulnerable </strong>:- Ignored for a period of time.</li></ul><p><strong>Fixing a vulnerability</strong></p><p>As soon as you trigger a vulnerability it is advisable to use the auto fix feature to automatically create a PR which has mostly the changes that need to be done. If the auto fix is not working then update the package locally in your dev machine. Once the package is updated then test the changes, if the tests are passing successful then push the changes to production. Then try to retest the Snyk scanner. The vulnerability should be mitigated or fixed.</p><p>The Snyk dashboard is really amazing to keep track of the vulnerabilities while working as an organisation. But Snyk also provides CLI tool that can be easily integrated while developing the project itself. Following are some of the useful Snyk CLI Commands that can improve your productivity two folds.</p><h4>Snyk CLI Commands</h4><p>Snyk’s Command Line Interface (CLI) offers a robust set of commands to help developers and security professionals secure their projects. There are a lot of CLI commands but I’ve curated the most frequently used and most used commands below:</p><ol><li>snyk test</li></ol><ul><li>Description: This is a fundamental Snyk CLI command that is used to test your project for any known vulnerabilities. It scans your project’s dependencies and provides a report on the vulnerabilities discovered.</li><li>Usage: Running snyk test in your project&#39;s directory will analyze your project&#39;s package manager files (e.g., package.json for node.js) and provide a summary of vulnerabilities found.</li></ul><p>2. snyk monitor</p><ul><li>Description: This command is used to push the project’s dependencies and vulnerabilities to the Snyk dashboard. It helps to collaborate with multiple team members in an organization.</li><li>Usage: Running snyk monitor command sets up continuous monitoring for your project and it provides real-time updates on vulnerabilities.</li></ul><p>3. snyk ignore</p><ul><li>Description: You can use this command to ignore vulnerabilities that you think the fix is not provided as of now. In such cases you can ignore the vulnerability for certain period of time or you can set them using --expiry flag.</li><li>Usage: To ignore a vulnerability, you can run snyk ignore &lt;vulnerability-id&gt;. The vulnerability-id is a unique identifier associated with the specific vulnerability. You can also ignore all vulnerabilities associated with a specific project by running snyk ignore — all-projects.</li></ul><p>4. snyk container test &lt;image&gt;:&lt;tag&gt; | snyk container test &lt;image&gt; — file=Dockerfile</p><ul><li>Description: You can also test the vulnerabilites inside docker images. You can test the docker image by providing the image name and its tag. If you want to test the docker image for custom images then you can provide the same command with this additional flag --file=Dockerfile</li><li>Usage: To test docker images use the first command to get the report of all the security vulnerabilites present in the image. If you need to do the same for local images then do the same with --file=Dockerfile flag.</li></ul><p>5. snyk iac test /path/to/config.yaml</p><ul><li>Description: This command allows you to scan your IaC files for known security issues or misconfigurations. This can be used on your local machine or in your CI environment.</li><li>Usage: Try to use the command like snyk iac test &lt;file&gt; where &lt;file&gt; is the path your IaC file (e.g, Terraform or CloudFormation script) that you want to analyze. Snyk will then analyze the file and provides a report on the security issues found.</li></ul><h4>Conclusion</h4><p>In this article, we have seen what is Snyk, how to use Snyk, common information presented in Snyk vulnerability board and also how Snyk CLI Commands work. We have seen the most frequently used commands and also its usage. Apart from these, we have seen how we can login to Snyk and setup the tool with Github or any other providers. We have also seen how to fix security vulnerability from the dashboard, its auto fix feature and the steps to be taken to remediate the issues. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat ……..</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20e393a4efff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: An Introduction to the Open-Source, Container Orchestration tool]]></title>
            <link>https://hemanthhari2000.medium.com/kubernetes-an-introduction-to-the-open-source-container-orchestration-tool-94672cbac3cf?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/94672cbac3cf</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Sun, 21 May 2023 10:45:09 GMT</pubDate>
            <atom:updated>2023-06-15T04:45:32.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand the concept of container orchestration and its importance in deployment of modern microservices applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHOIMmXKLCBd0ns1tTYr5A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">CHUTTERSNAP</a> on <a href="https://unsplash.com/photos/xewrfLD8emE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Nowadays with modern web services, users expect their applications to be available at any point in time and developers continuously do deployments to the applications. Running an application in such constrictive measure is a tedious task. Containerization is a concept where you can package your software into containers and ship it anywhere. You can release the application and also you can perform updates with no downtime. Now, Kubernetes makes sure that your containerized application run in its cluster with all the relevant resources that it needs. Hence, we can say that kubernetes is a platform designed to orchestrate containers in an efficient way.</p><p><strong>Kubernetes</strong> is a production-ready, open-source, system for automating deployment, scaling, and management of containerized applications. It was originally designed by Google and written in Go language but it is now maintained by the Cloud Native Computing Foundation. This makes it perfect fit for microservices applications. In this article we will be looking at kubernetes in detail and also be deploying a simple microservice posts application in a kubernetes cluster.</p><h4>Overview</h4><p>Let’s look at topics covered in this article.</p><ul><li>What is Kubernetes?</li><li>Why do we need Kubernetes in the first place?</li><li>Architecture of Kubernetes</li><li>Prerequisites</li><li>Implementation</li><li>Conclusion</li></ul><h4><strong>What is Kubernetes?</strong></h4><p>Kubernetes is an Open-Source, portable, extensible and production-grade container orchestration system for automating software deployment, scaling and management of containerized applications. It supports multiple deployment environments like on-premise, cloud and even virtual machines. Kubernetes can manage the execution of containerized applications across a network of devices. Using techniques that offer predictability, scalability and high availability, it is a platform created to fully manage the life cycle of containerized applications and services. With the help of Kubernetes, you can specify how your apps should operate and communicate with one another and the outside world. k8s is used as an alias for Kubernetes as it has 8 letters between k and s. I’ll be using interchangeably in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6nmKer92Gxt7llqfFu7hpg.png" /></figure><p>Kubernetes provides us with a lot of functionalities such as service discovery and load balancing, storage orchestration, automated rollouts and rollbacks, automatic bin packing, self-healing where the k8s restarts the failed containers, replaces, kills containers that do not respond to user-defined health checks and it also does secret and configuration management in which we can store and manage sensitive data like passwords, SSH keys and auth tokens. The deployment and updation of secrets and application configuration can be done without rebuilding the container image and also without exposing the secrets to your stack configuration.</p><h4>Why do we need Kubernetes in the first place?</h4><p>The necessity for organizations to satisfy customers micro service-driven architectural requirements is one of the main factors for k8s’ meteoric rise in popularity. This enables organizations to build independent and modular applications and deploy them in containers which is then managed by k8s. In production, k8s then manages all the containers which are deployed into something called as pods. Pods are k8s’ object that acts as a wrapper to the container and helps to manage the containers. It is always recommended to use only one container per pod to avoid high coupling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLDBDioc_oCP263mVaVcgQ.png" /><figcaption>Uses of k8s</figcaption></figure><p>Kubernetes helps us to solve the container managment problems. Deploying applications in containers is somewhat an easy task but the actual problem starts when we manage the containers. Let’s say the container is not responding or it failed. In such cases developers are expected to manually troubleshoot. But, Kubernetes makes this process automated and tries to restart or spin a new container or pods without any downtime. This allows multiple teams to work on individual applications which can be deployed with speed and agility. They are highly performant and scalable. It can also be integrated in the CI/CD pipleline which makes it even more developer friendly.</p><h4>Architecture of Kubernetes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g52wGPLbaSO7xuVgeUhTbA.png" /><figcaption>Architecture of Kubernetes</figcaption></figure><p>Above architecture is a high level architecture of Kubernetes. Basically, k8s consists of two major nodes called <strong>Master</strong> and <strong>Worker</strong> node. The actual architecture of k8s is pretty overwhelming and I will try to simplify as much as I can.</p><p>Let’s look into Master Node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68NjP-aaZJHj2h2X4Jy34g.png" /><figcaption>Master Node</figcaption></figure><p>Master node or the control plane makes global decisions about the cluster like scheduling, monitoring worker nodes and pods as well as detecting and responding to cluster events. There are basically four key processes and they are as follows:</p><ul><li>apiserver ( kube-apiserver )</li><li>schedulers ( kube-scheduler )</li><li>etcd</li><li>ctrl mgr ( kube-controller-manager )</li></ul><p><strong>apiserver ( kube-apiserver )</strong></p><p>The API server exposes the k8s API basically acting as a frontend to the control plane. This is designed to scale horizontally and you can also run several instances of kube-apiserver and manage traffic among those instances. It is often mistaken for being the master i.e, the face of k8s cluster.</p><p><strong>schedulers ( kube-scheduler )</strong></p><p>It continuously watches over the new pods request and assigns a node for newly requested pods. There are a lot of factors taken into consideration for scheduling decision and they are as follows: individual and collective resource requirements, hardware/software/policy constraints, affinity and anti-affinity specifications, data locality, inter-workload interference, and deadlines.</p><p><strong>etcd</strong></p><p>It is a distributed, key-value store used to store all cluster information and state information. It is the only stateful component in k8s and it is also called as the “Source of Truth”.</p><p><strong>ctrl mgr ( kube-controller-manager )</strong></p><p>The controller ensures the desired state is achieved in the cluster. They run in a single process but logically each controller is a separate process, but to reduce complexity they are all compiled into a single binary. It is a daemon that runs in a control loop. Examples: replication contoller, endpoint controller, serviceaccounts controller and more.</p><p>Let’s now look into Worker node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oD2Fty-lkHeoo15C6siCDw.png" /><figcaption>Worker Node</figcaption></figure><p>Worker node or node components run on every node, maintaining running pods and providing the kubernetes runtime environment. The main processes are as follows:</p><ul><li>kubelet</li><li>kube-proxy</li><li>container runtime</li></ul><p><strong>kubelet</strong></p><p>It is the main agent on the node that is often mistake for the node itself. It watches the apiserver for any work. It takes a set of PodSpecs and ensures the containers described in PodSpecs are running and is healthy or not. It directly report to master.</p><p><strong>kube-proxy</strong></p><p>It is a network proxy that runs on every node in the cluster. It assigns an IP to each pod with the help of CNI provider and they are primarily used to maint the service abstraction.</p><p><strong>container runtime</strong></p><p>It is responsible for running containers and mainly deals with container abstraction. It works with any OCI compliant container engine. It also supports <em>containerd</em>, <em>docker</em> and <em>rkt</em> as well.</p><h4>Prerequisites</h4><p>Let’s look at some prerequisites before we start deploying our posts application into k8s cluster.</p><ul><li>Kubernetes (Preferably use Rancher Desktop)</li><li>docker</li></ul><h4><strong>Implementation</strong></h4><p>Let’s start by taking our posts app where users can post and also have the ability to comment on each individual posts. The app is built using microservices architecture and there are mainly four services namely: <em>posts</em>, <em>comments</em>, <em>event-bus </em>and <em>query</em>.</p><ul><li><strong>Posts</strong> : A service that handles creation of Posts.</li><li><strong>Comments</strong> : A service that handles creation of Comments in a specific Post</li><li><strong>Event-Bus : </strong>Custom message broker service built from scratch, that handles sending message/events to other services.</li><li><strong>Query</strong> : A service that queries posts and comments posted.</li></ul><blockquote><strong>NOTE: This is not a step by step tutorial on how to build applications in node so, I will be focusing on how to deploy the app in kubernetes cluster. Please feel free to refer the </strong><a href="https://github.com/Hemanthhari2000/blog-microservices-app"><strong>source code</strong></a><strong> for more info.</strong></blockquote><p>The posts application is already built and this application is just a boilerplate. You can take any application and deploy them in kubernetes cluster. The main parts of this application is that you can create a post and comment on individual posts. Here I have also used a custom event bus to make things simple. You can use your own message brokers for the same if needed. Let’s see how we can deploy the application in kubernetes cluster.</p><p>Let’s create our deployment file for the frontend i.e for client. Create a file called client-depl.yml inside infra/k8s folder. As this file indicates that we need to deploy, we will be using k8s’ Deployment object and mentioning the same as kind: Deployment . The apiVersion is set to apps/v1 and the replicas is given as 1 for now. Make sure your matchLabels under selector matches the label specified under metadata of template , As it is required to match pod with the deployment. Another thing to take care is to containerize your services and push to a registry like docker hub. I have already containerized my services and pushed to docker hub. If you are following my source code then you should not have any issues with it. Once we specify all the necessary requirements, our Deployment file look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0cb4e068f71ad8f6d44af354c565e16/href">https://medium.com/media/a0cb4e068f71ad8f6d44af354c565e16/href</a></iframe><p>Now, after deployment we also need to have something called as a service file which will help us in networking between our pods. So let’s specify the service file as well. Here I will be using ClusterIP as this is a default one and it is used to communicate within the cluster itself. You can expose the Service to the public internet using an Ingress or a Gateway. We will use an Ingress to expose our app to the public later. The service should look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23587529f3268292c74f57869d4feec2/href">https://medium.com/media/23587529f3268292c74f57869d4feec2/href</a></iframe><p>That’s it for the client. We have our deployment and service which will be used to create a pod in our cluster and attach a network protocol to it as well. Now our client pod is created and can communicate with other resources as well. We will be using the same for rest of the services. We can specify both our deployment and service configuration in a single yaml file with — — — separated. With the similar configuration let’s look at the configuration for posts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b831571d9cceb9e39a8b3aee21875d9c/href">https://medium.com/media/b831571d9cceb9e39a8b3aee21875d9c/href</a></iframe><p>Similarly, for query service the deployment and service configurations are as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73edf1a65ec5dc8b97c815d573852e6a/href">https://medium.com/media/73edf1a65ec5dc8b97c815d573852e6a/href</a></iframe><p>For comments service the deployment and service configurations are as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e79465294898c82206a47af3153a39/href">https://medium.com/media/c9e79465294898c82206a47af3153a39/href</a></iframe><p>And finally, for event bus the deployment and service configurations are as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a786d849cb9286a4c80d0289c7ccb9a5/href">https://medium.com/media/a786d849cb9286a4c80d0289c7ccb9a5/href</a></iframe><p>As you can see for all the services we have created the deployment and service configurations. Now each of the services have their own deployment and a network protocol attached to them.</p><p>But the deployments are only accessible within the k8s cluster and not to the public. We want to connect from outside to the cluster so for this let’s create an Ingress service file as well to take the traffic from public and route it to the cluster. For this, I’ll be using the k8s’ Ingress object and specify some rules. Let’s install ingress-nginx controller from the instructions given in this <a href="https://kubernetes.github.io/ingress-nginx/deploy/#quick-start">page</a>.</p><p>Instead of specifying localhost let’s specify a domain like posts.com in our hosts file like this 127.0.0.1 posts.com , Once the host is defined let’s move to the individual route. For my application the route /posts/create should be handled by the posts service so the service name and the port number is given. Similarly, for the /posts endpoint it should be handled by the query service and for /posts/?(.*)/comments where the ?(.*) acts as a wildcard and allows all pattern. The comments service should be mentioned. and finally for this endpoint /?(.*) another wildcard which means all other routes except the ones mentioned above. Finally, the ingress file should look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae1b40ef66e259651c3f60ec5218c651/href">https://medium.com/media/ae1b40ef66e259651c3f60ec5218c651/href</a></iframe><p>This will make sure that the traffic from public is routed to the services inside the cluster properly. And that’s it. Phewww….. Yeah it was a really long process but yes it’s finally done. All we need to do now is to just apply all the configuration and to see if everything works fine or not. Apply all the yaml file using this command.</p><p>kubectl apply -f .</p><p>Once the services are deployed you can now head to the posts.com URL in your browser and see the application there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSqkZsCCugirrWPrc0wUYA.png" /><figcaption>Final Output</figcaption></figure><h4>Conclusion</h4><p>In this article, we saw what Kubernetes really is and why we use it. We have also deployed an existing application to k8s cluster. For the deployment, we wrote some configurations for each and every service that our application had. Deployment allows to create pods and manage them and Service allows to have a network rule witch which the communication can be established in and outside the cluster. Deploying applications to k8s cluster and managing the applications become very easy as k8s handles most of the work for us. All we have to do is just specify all the requirements, that’s all. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat …….</strong></p><h4>Additional Resources</h4><p><a href="https://spacelift.io/blog/kubernetes-tutorial">Kubernetes Tutorial for Beginners: Basic Concepts</a></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000">Hemanthhari2000 - Overview</a></li><li><a href="https://github.com/Hemanthhari2000/blog-microservices-app">GitHub - Hemanthhari2000/blog-microservices-app</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94672cbac3cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to the world of Terraform]]></title>
            <link>https://hemanthhari2000.medium.com/introduction-to-the-world-of-terraform-3b1802c24325?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b1802c24325</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 15:48:53 GMT</pubDate>
            <atom:updated>2023-04-16T15:48:53.249Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand the concept of Infrastructure-as-code (IaC) and it’s importance in managing cloud and on-prem resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jG2SkfAMeWpqyaR4" /><figcaption>Photo by <a href="https://unsplash.com/ja/@dianamia?utm_source=medium&amp;utm_medium=referral">C Dustin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Managing resources, especially effective resource management, is a tough job to do when it comes to microservices applications. In a microservices architecture or application, it is very difficult to manage multiple virtual machines or servers, disk space, inbound and outbound rules, virtual private clouds (VPCs), and other computing resources all at once. Since services are divided into their own components or nodes, it is very difficult to maintain the resources or keep track of them manually. This leaves an open door to automating such manual tasks. This is where the tool <strong>Terraform</strong> comes into play.</p><p><strong>Terraform</strong> is an open-source infrastructure-as-a-code (IaaC or IaC) tool built by HashiCorp that helps developers to create, manage, delete and version resources in both cloud and on-prem efficiently and safely. It is basically a tool where we can set up the infrastructure or destroy it completely with the help of few terraform commands. In this article we will be looking at how we can write terraform code and try to deploy our resources to AWS cloud.</p><h3>Overview</h3><p>Let’s look at some of the topics covered in this article.</p><ul><li>What is Terraform?</li><li>Why do we need Terraform or any IaC tools?</li><li>Prerequisites</li><li>Implementation</li><li>Conclusion</li></ul><h3>What is Terraform?</h3><p>Terraform is an open-source infrastructure-as-a-code software tool created by HashiCorp that lets users to set up an infrastructure using a simple, easy to understand, declarative configuration language known as HashiCorp Configuration Language (HCL), or optionally JSON. The idea behind IaC is that we write and execute the code to create, deploy, update and delete the infrastructure. Terraform tool lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features. It can also be used in a multi-cloud environment where one workflow is enough to manage other clouds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIqXo-cfKyJQfbOdMt8mJw.png" /></figure><p>Terraform leverages APIs (Application Programming Interfaces) in order to build and manage resources on cloud platforms and other services. Providers enable terraform to work with nearly any platform or service with an accessible API. There are multiple providers in terraform that manages different types of resources and services. There are providers like AWS (Amazon Web Services), Azure, GCP (Google Cloud Platform), Kubernetes, Oracle Cloud Infrastructure, GitHub and more, that are publicly available in the official <a href="https://registry.terraform.io/">Terraform Registry</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*XVqOYKKg9yNjyLGV8jK6vQ.png" /><figcaption>Terraform Flow (credit: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fdeveloper.hashicorp.com%2Fterraform%2Ftutorials%2Faws-get-started%2Finfrastructure-as-code&amp;psig=AOvVaw2XLlSIVg4AqzL37UJhp_3U&amp;ust=1681544831266000&amp;source=images&amp;cd=vfe&amp;ved=0CBEQjRxqFwoTCJizw-TwqP4CFQAAAAAdAAAAABAE">HashiCorp</a>)</figcaption></figure><p>The main steps involved in the terraform workflow consists of three basic stages.</p><ul><li><strong>Write:</strong> You determine resources that could span diverse cloud providers and services as a configuration files using HCL.</li><li><strong>Plan:</strong> Based on the configuration files you write, Terraform creates an execution plan that defines the whole infrastructure that can be created, modified, or destroyed.</li><li><strong>Apply:</strong> Once the plan is approved, Terraform will apply all the changes and provisions the specified infrastructure.</li></ul><h3>Why do we need Terraform or any IaC tools?</h3><p>Terraform or any other IaC tools for that matter, makes it easy to configure, modify and delete resources in cloud. Managing cloud resources is tedious since, the process of creating or setting up an infrastructure manually is a repetitive task. We need some sort of an automated tool that can set up the whole infrastructure in matter of minutes with minimal efforts from the users side. IaC tools such as terraform are widely used since, most of the work when it comes to provisioning is automated with the help of some configuration files. IaC tools help reduce the manual work needed in setting up infrastructure and makes the process automated. It can also help in setting up multiple infrastructures as the configurations are written as code hence, they can be reused multiple times.</p><p>Terraform is one of the widely used IaC tools by many developers especially in DevOps. DevOps engineers leverage the concepts of terraform for setting up multiple resources in cloud in a declarative approach. Terraform was also built as a DevOps first, software solution, since most of the use cases of terraform is based on DevOps and cloud computing. There are a plethora of providers available in terraform registry that makes the tool easily pluggable. Terraform also takes an immutable approach to infrastructure, reducing the complexity of upgrading or modifying your services and infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4SAtSLOAsLwBgZQbl_u0g.png" /><figcaption>Top IaC Tools (credit: <a href="https://scand.com/company/blog/infrastructure-as-code/">scand</a>)</figcaption></figure><p>The biggest reasons why people prefer terraform is because of the following:</p><ul><li>It supports multiple providers like AWS, Azure, GCP and more.</li><li>It is very flexible and also it can store local variables including passwords and cloud tokens on terraform registry in encrypted form.</li><li>It is portable as it mitigates the hassle of frequently switching providers.</li><li>It provides immutable infrastructure where configuration changes are done smoothly.</li><li>Terraform’s central registry allows users to collaborate with other teams and individuals on infrastructure.</li><li>Terraform basically does orchestration and not just configuration management.</li></ul><h3>Prerequisites</h3><p>Let’s look at some prerequisites before we start implementing terraform and deploy an instance in AWS cloud.</p><ul><li>Terraform</li><li>AWS CLI</li><li>AWS Account</li></ul><h3>Implementation</h3><p>Let’s check if we have all the prerequisites to start with our application deployment using terraform. First, let’s check whether terraform is installed in the system. Go ahead and run the following command in your terminal.</p><pre>terraform version</pre><p>You should get something like this, if you have terraform installed.</p><pre>Terraform v1.4.5<br>on darwin_arm64<br>+ provider registry.terraform.io/hashicorp/aws v4.63.0</pre><h4>Terraform Installation</h4><p>If terraform is not installed then please go ahead and install it using the following commands based on your OS. You can get more information regarding terraform installation <a href="https://developer.hashicorp.com/terraform/downloads"><em>here</em></a>.</p><ul><li>For Mac</li></ul><pre>brew install terraform</pre><ul><li>For Linux</li></ul><pre>wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg<br>echo &quot;deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main&quot; | sudo tee /etc/apt/sources.list.d/hashicorp.list<br>sudo apt update &amp;&amp; sudo apt install terraform</pre><ul><li>For Windows, you can use <a href="https://chocolatey.org/">Chocolatey</a>.</li></ul><pre>choco install terraform</pre><h4>AWS CLI</h4><p>If AWS CLI is not installed in your system then go ahead and follow the installation steps mentioned <a href="https://aws.amazon.com/cli/"><em>here</em></a><em>.</em></p><p>Once the installation is done, type the following command in your terminal to verify whether aws cli is installed successfully or not.</p><pre>aws help</pre><h4>AWS Account</h4><p>Make sure you have an AWS account with a full IAM access account. If you do not have an AWS account please create a new account (preferably, free-tier account) before you proceed with this implementation. In this implementation I will be using <strong>AWS free-tier account</strong>.</p><blockquote><strong>NOTE</strong>: This implementation will create some resources and it is <strong>recommended</strong> to use <strong>AWS free-tier account</strong>. If your account is <strong>not</strong> <strong>free-tier</strong> then <strong>you are responsible</strong> for any charges that may apply in AWS.</blockquote><p>We also need AWS Access Key and AWS Secret Access Key. If you don’t have these or you are not sure where to check for these credentials then please follow this <a href="https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html"><em>guide</em></a> to get your credentials.</p><p>Once you have the access keys then run the following command in your terminal and paste your AWS Access Key and AWS Secret Access Key values when prompted</p><pre>aws configure</pre><h4>Prepare your application to deploy</h4><p>As previously said, we will be deploying an existing application to the AWS cloud using terraform. I will be using a website called <a href="https://www.tooplate.com/"><em>Tooplate.com</em></a><em> </em>which provides free HTML templates which we can use. For this example, I will be using a template called <a href="https://www.tooplate.com/view/2128-tween-agency"><em>Tween Agency</em></a>.</p><p>You can use this link to download any tooplate template https://www.tooplate.com/zip-templates/&lt;TEMPLATE_UNIQUE_NAME&gt;.zip . The <strong>TEMPLATE_UNIQUE_NAME</strong> can be found from the template homepage URL https://www.tooplate.com/view/<strong>2128-tween-agency</strong>. Here, <strong><em>2128-tween-agency</em></strong> is the <strong>TEMPLATE_UNIQUE_NAME</strong></p><p>Let’s create our user data script that will run during the instance creation time. So, we will be using <strong>apache2</strong> to host our application locally in the instance. Create a file called <strong>user-data.sh</strong> and add in the following contents</p><pre>#!/bin/bash<br>sudo apt update<br>sudo apt install apache2 wget unzip -y<br>wget https://www.tooplate.com/zip-templates/2128_tween_agency.zip<br>unzip 2128_tween_agency.zip<br>sudo cp -r 2128_tween_agency/* /var/www/html/<br>sudo systemctl restart apache2</pre><p>We are just installing <strong>apache2</strong> server and also downloading the template or application and storing it in /var/www/html/ path when the instance is created for the first time. I have used a template from tooplate website to demonstrate how deployment happens in the AWS cloud using terraform. Feel free to use which ever application you want to deploy to the cloud.</p><p>Finally, phew…. We are now ready to write some terraform configuration files.</p><h4><strong>Terraform configuration</strong></h4><p>In a new directory or folder, create the following files, namely, <strong>main.tf</strong>, <strong>provider.tf</strong>, <strong>variable.tf</strong>.</p><pre>mkdir terraform-deploy-application &amp;&amp; cd terraform-deploy-application<br>touch main.tf provider.tf variable.tf</pre><p>Let’s add AWS as our provider in <strong>provider.tf</strong> file.</p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>Once, the provider is set then we can go ahead and initialise terraform to work with the following configuration files.</p><pre>terraform init</pre><p>Now, we can define our variables in <strong>variable.tf</strong> file.</p><pre>variable &quot;aws_ami_id&quot; {<br>  type    = string<br>  default = &quot;ami-0aa2b7722dc1b5612&quot; <br>}<br><br>variable &quot;aws_instance_type&quot; {<br>  type    = string<br>  default = &quot;t2.micro&quot;<br>}<br><br>variable &quot;my_ip&quot; {<br>  type        = string<br>  description = &quot;My Public IP Address&quot;<br>  default     = &quot;&lt;YOUR_PUBLIC_IP_ADDRESS&gt;/32&quot;<br>}</pre><p>Since, terraform uses HCL, we will be defining our variables like this. The <strong>ami id </strong>is the id of <strong>Ubuntu</strong> instance and we will be using <strong>t2.micro</strong> as our instance type. Lastly, make sure that you add in your public IP Address in you variable.tf file. We will be <strong>accepting traffic only from our IP</strong> and not from the internet.</p><p>Let’s configure our instance in <strong>main.tf</strong> file</p><pre>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami                    = var.aws_ami_id<br>  instance_type          = var.aws_instance_type<br>  user_data              = file(&quot;user-data.sh&quot;)<br>  vpc_security_group_ids = [aws_security_group.tween_sg.id]<br>  key_name               = &quot;tween_key&quot;<br>  tags = {<br>    Name = &quot;tween-agency-web&quot;<br>  }<br>}</pre><p>Here, we are configuring an instance and setting some properties such as security group, key pair and user data. We get the ami id and instance type from the variable file that we already specified. To use the variables from the variable file, we need to use it like this var.&lt;VARIABLE_NAME&gt;. AWS Instance need a security group that specifies some rules to our incoming and outgoing traffic.</p><p>Let’s look at configuring security groups.</p><pre>resource &quot;aws_security_group&quot; &quot;tween_sg&quot; {<br>  ingress = [<br>    {<br>      cidr_blocks      = [&quot;${var.my_ip}&quot;]<br>      description      = &quot;SSH from my IP only&quot;<br>      from_port        = 22<br>      to_port          = 22<br>      protocol         = &quot;tcp&quot;<br>      ipv6_cidr_blocks = []<br>      prefix_list_ids  = []<br>      security_groups  = []<br>      self             = false<br><br>      }, {<br>      cidr_blocks      = [&quot;${var.my_ip}&quot;]<br>      description      = &quot;HTTP&quot;<br>      from_port        = 80<br>      to_port          = 80<br>      protocol         = &quot;tcp&quot;<br>      ipv6_cidr_blocks = []<br>      prefix_list_ids  = []<br>      security_groups  = []<br>      self             = false<br>      }, {<br>      cidr_blocks      = [&quot;${var.my_ip}&quot;]<br>      description      = &quot;HTTPS&quot;<br>      from_port        = 443<br>      to_port          = 443<br>      protocol         = &quot;tcp&quot;<br>      ipv6_cidr_blocks = []<br>      prefix_list_ids  = []<br>      security_groups  = []<br>      self             = false<br>    }<br>  ]<br>  egress = [<br>    {<br>      cidr_blocks      = [&quot;0.0.0.0/0&quot;, ]<br>      description      = &quot;&quot;<br>      from_port        = 0<br>      to_port          = 0<br>      protocol         = &quot;-1&quot;<br>      ipv6_cidr_blocks = []<br>      prefix_list_ids  = []<br>      security_groups  = []<br>      self             = false<br>    }<br>  ]<br>}</pre><p>You can see that we add 3 rules for ingress which means incoming traffic and they are for SSH, HTTP and HTTPS. The value for cidr_blocks in ingress is a variable that is defined in variable.tf file. For egress the configuration is set to public since, our application is not communicating with any service or external server. If your application communicates with another service or server then make sure to change your egress configuration based on the application needs.</p><p>Finally, let’s look at our key pair and some output configuration so that we can ssh to our instances and display public dns of created instance on the terminal respectively.</p><pre>resource &quot;aws_key_pair&quot; &quot;tween_key_pair&quot; {<br>  key_name   = &quot;tween_key&quot;<br>  public_key = &quot;&lt;YOUR_PUBLIC_KEY&gt;&quot;<br>}<br><br>output &quot;Info_From_AWS&quot; {<br>  value = format(&quot;%s%s&quot;, &quot;ssh -i tween_key_pair ubuntu@&quot;, aws_instance.web.public_dns)<br>}<br><br>output &quot;AWS_Instance_URL&quot; {<br>  value = format(&quot;%s%s&quot;, &quot;URL: http://&quot;, aws_instance.web.public_dns)<br>}</pre><p>In the above snippet, make sure to create your public and private keys and add the public key in the public_key field. If you want to create a public and private key please use the following command to generate a public and private key.</p><pre>ssh-keygen -t rsa -b 2048</pre><p>Copy the public key and paste it in the public_key field specified in the above snippet. We will be using private key during login into the instance.</p><p>At last, your main.tf file should look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c768f7a3a156d92788d235b60e97152b/href">https://medium.com/media/c768f7a3a156d92788d235b60e97152b/href</a></iframe><p>That’s it, yes that’s it, we are done with our terraform configuration. It’s that simple. Note that we are not creating a new VPC here. We will be using the default VPC provided by AWS.</p><p>Now, let’s apply the terraform files, but first let’s format the terraform configuration files. Type the following command in the terminal</p><pre>terraform fmt</pre><p>Once, the files are formatted we can start to plan the infrastructure using the following command.</p><pre>terraform plan</pre><p>You should see all the necessary resources that will be added, modified or deleted and at the end you should see a short summary about the current changes. Here, we are going to add 3 resources to AWS cloud.</p><pre>....<br>....<br>}<br>Plan: 3 to add, 0 to change, 0 to destroy. </pre><p>The operation is indicated by using the following symbols</p><ul><li><strong><em>+ sign</em></strong><em> : </em>Resources to be created</li><li><strong><em>~ sign</em></strong><em> :</em> Resource to be modified</li><li><strong>-<em> sign</em></strong><em> :</em> Resource to be deleted</li></ul><p>During the plan phase, terraform compares the changes with present terraform state file and based on the operation type the changes will be applied. Once, the changes are applied, then it automatically updates the terraform state from the new state. Let’s now apply the changes.</p><pre>terraform apply</pre><p>This command will connect to your provider, in this case AWS and create the resources in the backend. You should see something like this in your terminal. All the changes are applied and at the end you can see the instance URL and ssh command to connect to your instance.</p><pre>Changes to Outputs:<br>  + AWS_Instance_URL = (known after apply)<br>  + Info_From_AWS    = (known after apply)<br>aws_key_pair.tween_key_pair: Creating...<br>aws_security_group.tween_sg: Creating...<br>aws_key_pair.tween_key_pair: Creation complete after 2s [id=tween_key]<br>aws_security_group.tween_sg: Creation complete after 5s [id=sg-094eb7446d68b5751]<br>aws_instance.web: Creating...<br>aws_instance.web: Still creating... [10s elapsed]<br>aws_instance.web: Still creating... [20s elapsed]<br>aws_instance.web: Still creating... [30s elapsed]<br>aws_instance.web: Creation complete after 36s [id=i-0ef3a312d2e2c3549]<br><br>Apply complete! Resources: 3 added, 0 changed, 0 destroyed.<br><br>Outputs:<br><br>AWS_Instance_URL = &quot;URL: http://ec2-44-203-194-152.compute-1.amazonaws.com&quot;<br>Info_From_AWS = &quot;ssh -i tween_key_pair ubuntu@ec2-44-203-194-152.compute-1.amazonaws.com&quot;</pre><p>Once the resources are created you can login to your AWS dashboard to see the resources that are being created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0T83bHyh3GP642RwZkaNA.png" /><figcaption>Instance created in AWS</figcaption></figure><p>Similarly, from the terminal we can copy the URL and paste it in the browser, you should see the application being deployed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYgOFEBJgKH1Pk-HK7VrdA.png" /><figcaption>Application deployed successfully</figcaption></figure><p>You can even ssh to your instance based on the command you see under output in the terminal. Make sure that you change the private key file permission using this command chmod 400 PRIVATE_KEY_FILENAME and then use the following command ssh -i &lt;PRIVATE_KEY_FILENAME&gt; ubuntu@xxx–xx–xxx–xx–xxx.compute-1.amazonaws.com to connect to the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*QU1aP5wTghHXnT_15Fjg1A.png" /><figcaption>Status of apache2 in the instance is running</figcaption></figure><p>Yaay… We have successfully deployed our application to AWS cloud. That’s how easy it is to deploy our resources to cloud. By using terraform you would have seen that we have a lot of control over the resources that we create. All we have to do is just configure the required resources in terraform file and then terraform will take care of creating the resources needed.</p><p>If you want to delete or terminate created resources in the cloud, just type the following command</p><pre>terraform destroy</pre><p>This command will destroy or terminate all the resources created in the cloud. While destroying the infrastructure, we are prompted about the changes. After we approve it the infrastructure will be destroyed.</p><pre>....<br>....<br>}<br>Plan: 0 to add, 0 to change, 3 to destroy.<br><br>Changes to Outputs:<br>  - AWS_Instance_URL = &quot;URL: http://ec2-44-203-194-152.compute-1.amazonaws.com&quot; -&gt; null<br>  - Info_From_AWS    = &quot;ssh -i tween_key_pair ubuntu@ec2-44-203-194-152.compute-1.amazonaws.com&quot; -&gt; null<br><br>Do you really want to destroy all resources?<br>  Terraform will destroy all your managed infrastructure, as shown above.<br>  There is no undo. Only &#39;yes&#39; will be accepted to confirm.<br>  Enter a value: yes<br>aws_key_pair.tween_key_pair: Destroying... [id=tween_key]<br>aws_instance.web: Destroying... [id=i-0ef3a312d2e2c3549]<br>aws_key_pair.tween_key_pair: Destruction complete after 2s<br>aws_instance.web: Still destroying... [id=i-0ef3a312d2e2c3549, 10s elapsed]<br>aws_instance.web: Still destroying... [id=i-0ef3a312d2e2c3549, 20s elapsed]<br>aws_instance.web: Still destroying... [id=i-0ef3a312d2e2c3549, 30s elapsed]<br>aws_instance.web: Destruction complete after 32s<br>aws_security_group.tween_sg: Destroying... [id=sg-094eb7446d68b5751]<br>aws_security_group.tween_sg: Destruction complete after 2s<br><br>Destroy complete! Resources: 3 destroyed.</pre><p>You can view the code for this demo in my <a href="https://github.com/Hemanthhari2000/terraform-deploy-application"><em>github</em></a><em>.</em></p><h3>Conclusion</h3><p>In this article, we have seen what is terraform, why do we use terraform and other types of IaC tools. We have also deployed an application to AWS cloud with all the necessary configurations. We have written configuration files for the instance, security group and key pair. Also we have seen how easy it is to destroy the whole infrastructure with just one line command. As you can see terraform is really flexible and it can be easily integrated into CI/CD pipelines and DevOps environment seamlessly. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://github.com/Hemanthhari2000/terraform-deploy-application">GitHub - Hemanthhari2000/terraform-deploy-application</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b1802c24325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection using Single Shot MultiBox Detection (SSD) and OpenCV’s Deep Neural Network (DNN)]]></title>
            <link>https://medium.com/featurepreneur/object-detection-using-single-shot-multibox-detection-ssd-and-opencvs-deep-neural-network-dnn-d983e9d52652?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d983e9d52652</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 18:54:25 GMT</pubDate>
            <atom:updated>2021-04-03T18:54:25.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Detection using Single Shot MultiBox Detection (SSD) and Deep Neural Network (DNN)</h3><p>Understand about Single Shot MultiBox Detector and OpenCV’s Deep Neural Network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7Zr5MciHA03yniuIbzoBQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@maxwbender?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Max Bender</a> on <a href="https://unsplash.com/s/photos/traffic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Object detection is so important in the world right now as it is used in many fields like Healthcare, Agriculture, Autonomous Driving, and more. It provides an efficient way of handling image classification by detecting the object in the image and letting us know where it is in the image using localization, That is, it creates a bounding box around the object. This may sound like just another image classification algorithm but it is super powerful in the current world. Self Driving Cars use object detection (a much-advanced version, obviously! ) to detect what is there in front of them. They are used in healthcare to understand and classify different types of tumors and diseases in the human body.</p><p>The Applications of Object Detection are endless. But what makes it more interesting is to be able to achieve such technology in real-time. This has been very challenging so far. By using a simple technique we can boost the performance of object detection in real-time drastically. This can be observed by an increase in FPS (Frames Per Second) and its faster processing of each frame. We will exactly discuss this methodology in this article by using OpenCV’s Deep Neural Network (or) simply called DNNs.</p><h3>Overview</h3><p>Let’s take a look at the contents that we will cover in this article.</p><ul><li>What is Object Detection?</li><li>What is Single Shot MultiBox Detector?</li><li>What is OpenCV’s Deep Neural Network (DNNs)</li><li>Prerequisites</li><li>Implementation of SSD Object Detection using DNNs</li><li>Conclusion</li></ul><h3>What is Object Detection?</h3><p>Object detection is a computer technology related to computer vision and image processing that deals with detecting instances of semantic objects of a certain class (such as humans, buildings, or cars) in digital images and videos. Well-researched domains of object detection include face detection and pedestrian detection. Object detection has applications in many areas of computer vision, including image retrieval and video surveillance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOFLtYtRweZfTKcpRwKI6A.png" /></figure><p>They are extensively used in computer vision tasks like image annotations, face recognition, face detection, object tracking, and many more. Not only that but they are also used to solve real-world problems like Automated CCTV surveillance where you can keep track of some objects that may cause some threats. Objects are tracked until any threat or abnormality is found. It can then be handled by recording the footage for a certain duration and alerting the respective authorities about it.</p><p>There are many methods to achieve Object Detection. Some of the methods used to achieve object detection are</p><ul><li><strong>Single Shot MultiBox Detector (SSD)</strong></li><li>Faster R-CNN</li><li>Histogram of Oriented Gradients (HOG)</li><li>Region-based Convolutional Neural Network (R-CNN)</li><li>YOLO (You Only Look Once)</li></ul><p>Some of these methods may be familiar to you. Out of all, we understand about SSD and implement it using OpenCV’s DNNs</p><h3><strong>What is Single Shot MultiBox Detector?</strong></h3><p>Single Shot MultiBox Detector is a deep learning model used to detect objects in an image or from a video source. Single Shot Detector is a simple approach to solve the problem but it is very effective till now. SSD has two components and they are the <strong>Backbone Model</strong> and the <strong>SSD Head</strong>. Backbone Model is a pre-trained image classification network as a feature extractor. Usually, the fully connected classification layer is removed from the model. SSD Head is another set of convolutional layers added to this backbone and the outputs are interpreted as the bounding boxes and classes of objects in the spatial location of the final layer&#39;s activations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wp5PBeyt2YpkeO2ET_f8TQ.png" /></figure><p>Instead of using a traditional sliding window algorithm, SSD divides the image as grids, and each grid cell responsible for detecting objects in that region of the image. If there is no object detected then we output it as nothing or to be more precise we will put a “0” indicating that there is no object found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qeps_JjDJCloUW9fn7mqBw.png" /></figure><p>What if there are many objects of the same instance in a single image. This is where Anchor Box comes into play. Anchor Boxes are simple boxes that are assigned with multiple anchors/prior boxes, which are predefined and have fixed size and shape within the grid cell. Based on this we are able to detect multiple objects in an image.</p><h3>What is OpenCV’s Deep Neural Network (DNNs)?</h3><p>OpenCV&#39;s Deep Neural Network (DNNs)is a module that can be used to train and test deep learning models. There is a framework that is used to train the model that is Caffe. We can even train the DNNs using just our CPUs or GPUs. Using just a CPU gives a pretty decent performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AL5N5YJxiLRQsHDJSSpzwA.png" /></figure><h3>Prerequisites</h3><p>All you need to run a simple Object Detection using SSD are:</p><ul><li>Python (Obviously)</li><li>OpenCV</li><li>Download the MobileNetSSD prototxt from <a href="https://github.com/chuanqi305/MobileNet-SSD/blob/master/voc/MobileNetSSD_deploy.prototxt"><strong><em>here</em></strong></a>.</li><li>Download the MobileNetSSD Caffe model from <a href="https://github.com/C-Aniruddh/realtime_object_recognition/blob/master/MobileNetSSD_deploy.caffemodel"><strong><em>here</em></strong></a>.</li></ul><p>Our Video looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*oe6DpxDsa_h6LlCPJrwCfA.gif" /></figure><p>That’s it, yeah that&#39;s pretty much it. Now, let&#39;s get started implementing our object detection, shall we?</p><h3>Implementation of SSD Object Detection using DNNs</h3><p>Go ahead and open your project folder and create a new folder saying object detection. Create a file called <em>ssd-object-detection.py .</em></p><ul><li><strong>Imports</strong></li></ul><pre>import numpy as np<br>import cv2</pre><p>That’s all for our imports. Now, let&#39;s start defining some constants.</p><pre>PROTOTXT = &quot;MobileNetSSD_deploy.prototxt&quot;<br>MODEL = &quot;MobileNetSSD_deploy.caffemodel&quot;<br>INP_VIDEO_PATH = &#39;cars.mp4&#39;<br>OUT_VIDEO_PATH = &#39;cars_detection.mp4&#39;<br>GPU_SUPPORT = 0</pre><pre>CLASSES = [&quot;background&quot;, &quot;aeroplane&quot;, &quot;bicycle&quot;, &quot;bird&quot;, &quot;boat&quot;, &quot;bottle&quot;, &quot;bus&quot;,  &quot;car&quot;, &quot;cat&quot;, &quot;chair&quot;, &quot;cow&quot;, &quot;diningtable&quot;, &quot;dog&quot;, &quot;horse&quot;, &quot;motorbike&quot;, &quot;person&quot;, &quot;pottedplant&quot;, &quot;sheep&quot;, &quot;sofa&quot;, &quot;train&quot;, &quot;tvmonitor&quot;]</pre><pre>COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))</pre><p>Now let’s load the model. If you have CUDA GPU support for DNNs then go ahead and set the backend for it.</p><pre>net = cv2.dnn.readNetFromCaffe(PROTOTXT, MODEL)<br>if GPU_SUPPORT:<br>    net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)<br>    net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)</pre><p>Now, open your video capture and start reading each frame. Then set your model and start using the pre-trained model to detect objects from frames.</p><pre>while True:<br>    ret, frame = cap.read()<br>    if not ret:<br>       break<br>    h, w = frame.shape[:2]<br>    blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)<br>    net.setInput(blob)<br>    detections = net.forward()<br>    for i in np.arange(0, detections.shape[2]):<br>       confidence = detections[0, 0, i, 2]<br>       if confidence &gt; 0.5:<br>           idx = int(detections[0, 0, i, 1])<br>           box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])<br>           (startX, startY, endX, endY) = box.astype(&quot;int&quot;)<br>           label = &quot;{}: {:.2f}%&quot;.format(CLASSES[idx],confidence*100)<br>           cv2.rectangle(frame, (startX, startY), (endX, endY),    COLORS[idx], 2)<br>           y = startY - 15 if startY - 15 &gt; 15 else startY + 15<br>           cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)</pre><p>That’s it we are done with the object detection. It is as simple as that. Now after all this your code should look this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/516114fd53d900d1757e0bd611cb0f55/href">https://medium.com/media/516114fd53d900d1757e0bd611cb0f55/href</a></iframe><p>Just run the code. if everything is perfect then your output should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*koq1MYwPyrJMvD6pQuUEyQ.gif" /></figure><p>That’s it. We implemented object detection with such good fps and accuracy. You can use it with CUDA DNNs installed and by doing that you will see a lot of improvement in your model and you will easily get much higher accuracy.</p><h3>Conclusion</h3><p>In this article, we have seen object detection using the SSD model and OpenCVs DNNs. We understood how exactly SSD works with OpenCVs DNNs. We also implemented a simple object detection using a pre-trained model with much higher accuracies. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d983e9d52652" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/object-detection-using-single-shot-multibox-detection-ssd-and-opencvs-deep-neural-network-dnn-d983e9d52652">Object Detection using Single Shot MultiBox Detection (SSD) and OpenCV’s Deep Neural Network (DNN)</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Micro Web Framework Flask]]></title>
            <link>https://medium.com/featurepreneur/introduction-to-micro-web-framework-flask-78de9289270b?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/78de9289270b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 18:52:45 GMT</pubDate>
            <atom:updated>2021-04-03T18:52:45.103Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand the concept of micro web framework Flask in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzIo5Uj9RhvrPU0KjeaDcw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lucasfranco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lucas Franco</a> on <a href="https://unsplash.com/s/photos/building?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Web Development in today’s time is very important for any business. Many big companies and startups rely on a great website to attract many customers. Web Development for a Data Scientist is essential today because to a customer or user, demonstrating the code and showing the output in a terminal form wouldn&#39;t make any sense if he is not from a programming background. This may lead to rejections. To show the functionality of the machine learning or deep learning model, deploying it as a website or a web app makes sense as it is easy to show users the core functionality in a graphical form which tends to attract more users.</p><p>Web Development has become quite the way for Data Scientist or any AI enthusiast to show his algorithm, project that he has worked on. This is why most machine learning and deep learning engineers use some web development to deploy their models. But, how can a Data Scientist quickly deploy his/her AI model? Well, to answer that question we have something called <strong>Flask</strong> which helps us achieve it.</p><h3>Overview</h3><p>Let’s take a look at the contents that we will cover in this article.</p><ul><li>What is Flask?</li><li>Why use Flask?</li><li>Merits of using Flask</li><li>Prerequisites</li><li>Installing Flask</li><li>Implementation of Flask</li><li>Conclusion</li></ul><h3>What is Flask?</h3><p>Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. However, Flask supports extensions that can add application features as if they were implemented in Flask itself. Extensions exist for object-relational mappers, form validation, upload handling, various open authentication technologies, and several common framework-related tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fkgtfwm-q3Cbm4gt7ZiRpg.png" /></figure><p>Flask is very easy to learn and quick to implement. It is preferred by many Data Scientists as it is quick to implement and easy to show a demo of their models. As Flask is written in Python, Developers who are familiar with Python find it no difficult to learn Flask. Though Flask has no additional tools or libraries that a normal framework would have, it makes it easy to implement other services like databases.</p><h3>Why use Flask?</h3><p>Flask is a lightweight Web Server Gateway Interface Web Application (WSGI) framework. It gives the developer varieties of choice when developing web applications, it provides you with the necessary tools to build and deploy a web application. It does not enforce any dependencies or give a fixed project structure like other Python Web Frameworks like Django offers. This adds to the advantage side by making it useable by many developers. The website can be on anything, but still, it allows the developers the opportunity to use some extensions provided by the community that allows you to add more functionality to the web application.</p><p>Because of its simplicity, Flask is used in top tech companies like</p><ul><li>Netflix</li><li>Reddit</li><li>Airbnb</li><li>Lyft</li><li>Mozilla</li><li>Uber</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTBP2lmuF9nhZhA5zlnJyw.png" /></figure><h3>Merits of using Flask</h3><p>As said above Flask is a lightweight Web Server Gateway Interface (WSGI) web application framework. It has minimal or no external libraries. It is used to create a simple website and then scale it up to complex applications. Below are some of the merits of using Flask.</p><ul><li><strong>Easy to Use</strong>: The Flask framework is easy to understand, which makes it perfect for beginners. The simplicity in the flask framework enables the developer to navigate around and create the application easily.</li><li><strong>Very Flexible</strong>: Most of the Flask components can be altered. It allows users to customize the website.</li><li><strong>Testing</strong>: It allows unit testing through its integrated support, built-in development server, fast debugger, and restful request dispatching. Makes testing much faster.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gEP8G1WkkyGch4xUEYfRw.png" /></figure><h3>Prerequisites</h3><p>You’ll need the following to run Flask.</p><ul><li>Python ( latest version recommended )</li><li>Flask ( latest version recommended )</li><li>virtualenv ( latest version recommended )</li></ul><p>That’s it we are all set to install Flask and create a simple website, shall we?</p><h3><strong>Installing Flask</strong></h3><p>Installing Flask is pretty easy. All you have to do is just type one command. That’s it.</p><p><strong>Note: It is advised to use a virtual environment for any Python project you start.</strong></p><p>First, install the virtualenv package using pip the command.</p><pre>pip install virtualenv</pre><p>Go ahead and create your virtual environment using the following.</p><pre>virtualenv flask_env</pre><p><strong>Note: Here </strong>flask_env<strong> is the name of the environment created.</strong></p><p>Now activate your virtualenv and install the requirements.</p><p><em>For Linux based systems</em></p><pre>source flask_env/bin/activate</pre><p><em>For Windows,</em></p><pre>flask_env\Scripts\activate</pre><p>After activation install Flask.</p><pre>pip install flask</pre><p>This should install all the necessary Flask modules.</p><h3>Implementation of Flask</h3><p>Before implementing Flask, we will just take a look at our project structure.</p><pre>.<br>├── app.py<br>└── templates<br>    └── index.html</pre><pre>1 directory, 2 files</pre><p>All we did was to create an app.py and then a folder called templates and inside templates we have index.html .</p><p><strong>Note: You should also have a folder called </strong>flask_env<strong> which is our flask environment.</strong></p><p>Now jump into your code editor and create a new file called app.py and import Flask and render_template to render HTML onto the webpage.</p><pre>from flask import Flask, render_template</pre><p>Now use Flask to create an endpoint and render a template there.</p><pre>app = Flask(__name__)</pre><pre>@app.route(&#39;/&#39;)<br>def home():<br>    return render_template(&#39;index.html&#39;)</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>that’s it our app.py is done.</p><p>Now open Our index.html and type some content that you want to display onto the webpage.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>        &lt;title&gt;First Flask App&lt;/title&gt;</pre><pre>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;h1&gt;First Flask Web App&lt;/h1&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>now we are almost done. Just open your terminal and type</p><pre>python app.py</pre><p>this should run the flask app and you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*fxz70h1yvC7yTic4mraV0g.png" /></figure><p>Now open your localhost browser that is <a href="http://localhost:5000/">http://localhost:5000/</a> to see your flask web app render your HTML there. You should see an output similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*-AEt7D9TPzjF6DWVP1hIwA.png" /></figure><p>That’s it we installed Flask and implemented a very simple Flask application. Now it is your time to create some cool web apps and dynamic content and amaze everyone. If you are an AI enthusiast then feel free to deploy your model as a Flask application and share it with others. For a simple demonstration of how to machine learning models using Flask check out my article about it here.</p><p><a href="https://medium.com/featurepreneur/build-your-own-chatbot-in-python-with-ajax-8021cacb225">Build your own Chatbot in Python with AJAX.</a></p><h3>Conclusion</h3><p>In this article, we have seen Flask and its importance in today&#39;s world. We even saw some of the major companies that use Flask. A simple implementation on how to install Flask and use it is demonstrated. Flask opens a huge set of possibilities and if you want to create awesome applications quickly, Flask is your go-to. They are perfect to deploy your AI models. Explore more about Flask I am sure you will be amazed at how simple yet powerful it is. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78de9289270b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/introduction-to-micro-web-framework-flask-78de9289270b">Introduction to Micro Web Framework Flask</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to the in-memory datastore Redis]]></title>
            <link>https://medium.com/featurepreneur/introduction-to-the-in-memory-datastore-redis-e1ba0a3d3f20?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ba0a3d3f20</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 17:58:01 GMT</pubDate>
            <atom:updated>2021-04-01T17:58:01.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand the concept of distributed, in-memory key-value database, cache, and message broker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3WFK0x8rKzCuMClaaDGWw.jpeg" /></figure><h3>Introduction</h3><p>Modern world web applications require a lot of things up and running on the server to serve the purpose of users. Many developers don&#39;t know about the factors which can ruin a user’s experience. It depends on how well the code is optimized, how the server responds, how well the database is integrated and so. This may depend on the framework or the language developers use. But, Developers can optimize their application which can significantly increase the overall performance. One such thing they can optimize to increase the performance is by using efficient database connection and utilizing it for quick responses. Well, here is where <strong>Redis</strong> comes into play.</p><h3>Overview</h3><p>Let’s take a look at the contents that we will cover in this article.</p><ul><li>What is Redis?</li><li>Where is Redis used?</li><li>Merits of using Redis</li><li>Installing Redis</li><li>Implementation of Redis</li><li>Conclusion</li></ul><h3>What is Redis?</h3><p><em>Redis</em> (or) <em>Remote Dictionary Server</em> is an open-source, in-memory data structure store, used as a distributed, in-memory key-value database, cache, and message broker, with optional durability. Redis supports different kinds of abstract data structures, such as strings, lists, maps, sets, sorted sets, HyperLogLogs, bitmaps, streams, and spatial indexes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1d88Q8NNrRv6kjf7Ssw4g.png" /></figure><p>Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster. Redis supports cross platforms which means that you can simply run Redis on Windows, Mac, or any Linux-based systems. Redis recommends using Linux-Based Systems on their Official Documentation <a href="https://redis.io/topics/introduction">page</a>.</p><h3>Where is Redis used?</h3><p>Redis can be used in a lot of applications that we use in our everyday life. Redis helps to store and retrieve data in memory very easily and efficiently. Some of the use cases of Redis are:</p><ul><li>Caching</li><li>Messaging and Queue</li><li>Session Store</li><li>Machine Learning</li><li>Real-Time Analytics</li></ul><p><strong>Caching: </strong>Redis is perfect for implementing a high in-memory cache to decrease data access latency and increase throughput. They can respond in milliseconds which makes it pretty fast and it also enables you to easily scale for higher loads without spending a huge amount of money for just the backend.<strong> </strong>Database query results caching, persistent session caching, web page caching, and caching of frequently used objects such as images, files, and metadata are all popular examples of caching with Redis.</p><p><strong>Messaging and Queue: </strong>Redis also supports Pub/Sub (Publish and Subscribe) with pattern matching and a variety of data structures. This enables Redis to support high-performance messaging, chat rooms, and server intercommunication. We have used a lightweight queue using the Redis List data structure. Lists are ideal for a variety of applications that needs a reliable message broker as it offers atomic operations as well as blocking capabilities.</p><p><strong>Session Store:</strong> For internet-scale applications, Redis is the best choice as it supports in-memory. It provides sub-millisecond latency, scale, and resiliency required to manage session data like session state, credentials, and more.</p><p><strong>Machine Learning: </strong>As we know, Machine Learning models can be a slow and time-consuming process to load some data as inputs and process it to produce outputs. This process can be handled by Redis and the application performance can be increased significantly. With this, many machine learning models can be deployed in production and have a smooth functionality with users.</p><p><strong>Real-Time Analytics:</strong> As Redis handles data with sub-millisecond latency, it is the perfect choice for real-time analytics like social media analytics, ad targeting, personalization, Artificial Intelligence-based applications, Cyber Security, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO95IDN7-AUMmJI6phcRrQ.png" /></figure><h3>Merits of using Redis</h3><p>Redis is great for delivering results faster and managing data that is to store and retrieve it. Some merits of Redis are:</p><ul><li><strong>Faster Database responses</strong>: They store data in RAM, rather than on an HDD (Hard Disk Drive) or SSD (Solid State Drive).</li><li><strong>Has Control over Lifetime of a Data</strong>: Redis supports the Time to Live (TTL) feature where if the keys are set in TTL mode with the duration time to live, data will expire after this time elapses.</li><li><strong>Key-Based Access</strong>: Redis is based on a key-value model. Key-Based access allows for extremely efficient access times. We can access the data using Redis GET and SET semantics. They are very fast though, they can perform around 110, 000 SETs per second and around 81, 000 GETs per second.</li><li><strong>Language Support</strong>: Redis is supported by most of the programming languages like Python, C, C++, Java, JavaScript, and more. You can access the full language support <a href="https://redis.io/clients">here</a>.</li></ul><p>Okay, enough talking though, let’s try some Redis for ourselves, shall we….</p><h3>Installing Redis</h3><p>First of all, open your terminal and start typing the following:</p><p><strong>Note: I am using Ubuntu here for windows or other operating systems you can install it by downloading from the official Redis </strong><a href="http://redis.io/"><strong>website</strong></a><strong>.</strong></p><p><em>Update your Packages</em></p><pre>sudo apt-get update<br>sudo apt-get upgrade</pre><p>Install Redis Server</p><pre>sudo apt-get install redis-server</pre><p>This would have installed Redis on your Ubuntu System. Now follow one more command and you good to go.</p><pre>sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.default</pre><p>That’s it. Redis is perfectly installed and to make sure it works use the following command.</p><pre>redis-cli</pre><p>this should have opened a Command Line Interface with your localhost and port number in it.</p><pre>127.0.0.1:6379&gt; </pre><p>if your output looks something like this then congratulations you have to install Redis on your Ubuntu.</p><h3>Implementation of Redis</h3><p>Let’s get started with a simple implementation of Redis. So, go ahead and start your terminal and start the Redis server using the <strong><em>redis-cli</em></strong> command. Here, we used very simple SET and GET operations but you can definitely explore more such commands from <a href="https://redis.io/commands"><strong><em>here</em></strong></a>.</p><ul><li><strong>SET</strong> in Redis: It sets a value to a key as shown below (used to store data).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*KEZDpHf3oMUdFTbZ6lsHqg.png" /></figure><pre>&gt; SET car &quot;Audi&quot;</pre><ul><li><strong>GET</strong> in Redis: It gets the value using the key as shown below (used to retrieve data).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*JOuzSkk4oUPOMiNxzDWxgA.png" /></figure><pre>&gt; GET car</pre><ul><li><strong>SET</strong> using Key Spaces</li></ul><pre>&gt; SET server:name google<br>&gt; SET server:port 8080</pre><ul><li><strong>GET</strong> using Key Spaces</li></ul><pre>&gt; GET server:name<br>&gt; GET server:port</pre><ul><li>Use <strong>FLUSHALL</strong> to Remove all the data</li></ul><pre>&gt; FLUSHALL </pre><p>after executing all the commands our terminal should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*Gy1DlKoqLCurgX0cLzTFgQ.png" /></figure><h3><strong>Conclusion</strong></h3><p>In this article, we have seen Redis and its functionalities. We went through the concept of in-memory structure store, message broker, cache, and its effective use in the real-world scenario. We even installed Redis on Ubuntu and learned some Redis commands that help us store and retrieve data efficiently. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ba0a3d3f20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/introduction-to-the-in-memory-datastore-redis-e1ba0a3d3f20">Introduction to the in-memory datastore Redis</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Asynchronous Task Queueing  Celery]]></title>
            <link>https://medium.com/featurepreneur/introduction-to-asynchronous-task-queueing-celery-be5fac364350?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5fac364350</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 17:56:39 GMT</pubDate>
            <atom:updated>2021-04-01T17:56:39.526Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Asynchronous Task Queueing Celery</h3><p>Understand the concept of an asynchronous task queue, distributed message passing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQbHirTUi6F8aPlVqH4SjQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cbarbalis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Barbalis</a> on <a href="https://unsplash.com/s/photos/crowd?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Python is one of the best programming languages out there for web development. It is easy to learn and is flexible like most of the web applications on the internet. Task queue (or) Job queue plays an important role in a web application where it schedules programs (or) jobs to the queue for batch processing. This enables services (or) programs to execute in the background without disturbing other processes. This Task Queue is designed for asynchronous work. So, how can one actually achieve Task Queue? Well, we can by using Celery.</p><h3>Overview</h3><p>Let’s take a look at the contents that we will cover in this article.</p><ul><li>What is Celery?</li><li>Why use Celery?</li><li>Merits of using Celery</li><li>Prerequisites</li><li>Installing Celery</li><li>Implementation of Celery</li><li>Conclusion</li></ul><h3>What is Celery?</h3><p><em>Celery</em> is an open-source, simple, flexible, distributed system to process vast amounts of messages while providing operations with the tools required to maintain such a system. It’s a task queue with a focus on real-time processing, while also supporting task scheduling. Celery is written in Python, but it can be implemented in any language as the protocol is the same for all. It is a cross-platform software which means you can set up Celery in any Operation System.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tkwTvFagDpM9HCdJsn1e2g.png" /></figure><h3>Why use Celery?</h3><p>One of the most difficult parts of the Python web application stack is understanding and implementing asynchronous task queues or job queues. Task Queues are very important to serve users with better functionalities. If users are not satisfied, all the effort put into the application will go in vain. So, it is better to use a task queue like Celery to avoid such scenarios in real life.</p><p>As a developer, we want our application to be fast and responsive to all the requests that it gets. As we know that each request ties up to a worker process until the response is finally finished. In a normal application, we would have overloaded our process worker which eventually slows down our applications. But, we don&#39;t want that do we? of course not, so this is the main reason why we use Celery. Celery makes it easy to put tasks in a queue that can be executed later. By doing this we are improving our WSGI server response time and also perform some other important tasks while this executes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*6KqtrP8sP5mAn9xXYBQD5Q.png" /></figure><h3>Merits of using Celery?</h3><p>The following are some of the merits of using Celery.</p><ul><li><strong>Open-Source</strong>: As explained above, Celery is Open-Source software written in Python. This enables small businesses to use such technology and even modify some changes in the official source code.</li><li><strong>Broker Support</strong>: Celery supports multiple message brokers like RabbitMQ and Redis. Which are also the recommended ones. Also, we have some additional brokers like MongoDB, Amazon SQS, CouchDB, IronMQ, Django ORM are supported too.</li><li><strong>Easy to Install</strong>: Celery is very easy to install and there are no workarounds needed. It is pretty straightforward though.</li><li><strong>Web Framework Integrations</strong>: It also integrates itself with multiple web frameworks, including Django, Flask, Pyramid, Pylons, web2py, Tornado, and Tryton.</li></ul><h3>Prerequisites</h3><p>You’ll need the following to successfully run celery.</p><ul><li>Python (latest version recommended)</li><li>Redis (or) RabbitMQ installed for broker management.</li><li>sqlite3</li><li>IPython (optional)</li></ul><p><strong><em>Note: In this article, we are using “</em>Redis<em>” as our broker. You can use “RabbitMQ” and get the broker URL.</em></strong></p><h3>Installing Celery</h3><p>Before installing Celery, install the following using the commands shown:</p><pre>pip install redis<br>pip install sqlalchemy</pre><p>All set, Let’s get started with the installation of Celery. As explained above installing Celery is the easiest thing. Just type this command in your command line (or) terminal.</p><pre>pip install celery</pre><p>That’s it our installation is complete.</p><h3>Implementation of Celery</h3><p>Open up your code editor and create a new python file called “<strong><em>tasks.py</em></strong><em>”. </em>Now, import celery and create an app using celery and pass the broker URL and also specify the database backend. In this case, the broker URL is from <strong>Redis</strong> and the database backend is from <strong>SQLite3.</strong></p><pre>from celery import Celery</pre><pre>app = Celery(<br>    name = &#39;tasks&#39;,<br>    broker = &#39;redis://localhost:6379&#39;, <br>    backend = &#39;db+sqlite:///db.sqlite3&#39;)</pre><p>Now go ahead and create a decorator as follows:</p><pre>@app.task<br>def absoluteSub(a, b):<br>    return abs(a - b)</pre><p>now you can see that we have a simple function that outputs absolute value when subtracted. This function is wrapped in a decorator called to <em>task</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ebd3bb5a81c5a387dac19b81bf97f97/href">https://medium.com/media/9ebd3bb5a81c5a387dac19b81bf97f97/href</a></iframe><p>Now, let&#39;s get back to our terminal and start our celery server and see if everything is connected or not.</p><pre>celery -A tasks worker --loglevel=info</pre><p><strong><em>Note: Here in the above argument “</em>tasks<em>” is the name of our python file that we created.</em></strong></p><p>The above command should set everything up and we should get an output that looks something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*tn8pTJaMKY_bH8w5plga5g.png" /></figure><p>As you can see we are connected to the Redis broker using the URL and also our main program is ready.</p><p>Next, open up a new terminal and run the following commands</p><pre>from tasks import absoluteSub<br>result = absoluteSub.delay(10, 20)<br>result.status<br>result.get()</pre><p>This should give us the output like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*z-ZpsGuvx7wADMtBu-I53w.png" /></figure><p>We get the status as ‘SUCCESS’ indicating that the process is done, and also we get the result as “10” which is as expected. But, let us check if we got the log of this process in the database backend that we connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMI8WYpOzl4DifE7DF_9Ig.png" /></figure><p>We can see that our process was executed and we can also see the status and task_id that celery provides.</p><p>Now, it is your time and creates some awesome projects that use task queueing with Celery to boost up the performance of your project.</p><h3>Conclusion</h3><p>In this article, we have seen Celery and its functionalities. We went through the concept of Asynchronous Task Queue and its effective use in the real-world scenario. We even installed Celery and implemented some task queueing. We connected our Celery to Redis broker and also we used the SQLite3 database as our backend to store the result and logs that Celery throws. I hope this article was useful to you all. Will see you in my next article until then, as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5fac364350" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/introduction-to-asynchronous-task-queueing-celery-be5fac364350">Introduction to Asynchronous Task Queueing  Celery</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Parallel Computing in Python using Dask]]></title>
            <link>https://medium.com/featurepreneur/introduction-to-parallel-computing-in-python-using-dask-4863838994ae?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4863838994ae</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Tue, 30 Mar 2021 17:47:10 GMT</pubDate>
            <atom:updated>2021-03-30T17:47:10.940Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand the basics of parallel computing and Dask</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3AqxLBsNWwEfll6MuiW9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@luchox23?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luis Gonzalez</a> on <a href="https://unsplash.com/s/photos/processor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Python is one of the fastest-growing programming languages in the world right now. It is widely used in the field of data science and research. The reason python being so famous is because of its nature and its libraries like NumPy, Pandas, scikit-learn and so. These libraries are powerful to build models, train and also visualize them. But, this comes at a price. Though they are powerful libraries, they run on single-core, which slows down the process drastically.</p><p>This is the reason why Python is slow while doing machine learning computations. So, how can we speed up this process? Can it be done? Is it possible to make python code faster? Of Course python computation can be boosted using <strong>Dask</strong>.</p><h3>Overview</h3><p>Let’s take a look at the contents that we will cover in this article.</p><ul><li>What is Parallel Computing?</li><li>What is Dask?</li><li>Prerequisites</li><li>Installing Dask</li><li>Implementation of Dask</li><li>Conclusion</li></ul><h3>What is <strong>Parallel Computing?</strong></h3><p>Parallel computing is a type of <strong>computing</strong> architecture in which several processors simultaneously execute multiple, smaller calculations broken down from an overall larger, complex problem.</p><p>As soon as the program starts executing, it starts to divide the problem into several smaller problems or into several subtasks. Each subtask is executed independently without any interference of an external force and the result is finally added together to get the resultant output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*kZslxiC0xzz5pxF2haxIQg.png" /></figure><h3>What is Dask?</h3><p>Dask is an open-source and flexible library for parallel computing written in Python. It is a platform to build distributed applications. It does not load the data immediately but, it only points to the data and only the necessary data is used or showed to the user. Dask has the functionality to use more than a single-core processor and it uses parallel computing which makes it very fast and efficient with huge datasets. It avoids errors related to memory overflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*u86pJOiu7Uin4C-ik-1qvg.png" /></figure><p>Dask has two families of task schedulers:</p><ul><li><strong>Single machine scheduler</strong>: This scheduler provides basic features on a local process or thread pool. This scheduler was made first and is the default. It is simple and cheap to use. It can only be used on a single machine and does not scale.</li><li><strong>Distributed scheduler</strong>: This scheduler is more sophisticated. It offers more features, but also requires a bit more effort to set up. It can run locally or distribute across a cluster.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*JfHfDOJOUkZCHk6rpNQi4Q.png" /></figure><h3>Prerequisites</h3><p>All you need prior to setup dask are</p><ul><li>Python (latest version recommended)</li><li>Anaconda with Jupyter Notebook (recommended)</li></ul><h3>Installing Dask</h3><p>If you have Anaconda then, it comes preinstalled in your environment. But, if for some reason you don&#39;t have Dask preinstalled then go ahead with the following.</p><ul><li>Create a new Conda Environment</li></ul><pre>conda create -y -n dask_env </pre><ul><li>Activate your Conda Environment</li></ul><pre>conda activate dask_env</pre><ul><li>install dask</li></ul><pre>conda install dask </pre><p>(or)</p><pre>pip install dask </pre><p>Note: This will only install a few core packages related to Dask. If you want everything then go ahead and paste this command.</p><ul><li>Install all Dask packages</li></ul><pre>python -m pip install &quot;dask[complete]&quot;</pre><p>That’s it, you have just installed all the required Dask packages. Now you can go ahead and start messing with Dask.</p><h3>Implementation of Dask</h3><p>Let’s get started with a simple implementation of Dask. But before that, we need to understand why we are using Dask right? so, for that let us get back to our command prompt and type the following.</p><pre>import numpy as np<br><br>dataset = np.ones((100000, 1000, 1000))</pre><p>As you can see that we used the NumPy library and we generated some data using the <em>np.ones()</em> function. Here, it is clearly visible that the dimensions are quite big. Now let us execute the following and see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KX2-l6_4W0retl2ZFTdPLw.png" /></figure><p>Oh, snap!!! see, we got an error saying <strong><em>MemoryError </em></strong>which means that NumPy was not able to store such a huge amount of data. As a Data Scientist, it is our job to handle large datasets efficiently. So, let’s use Dask and see what happens.</p><pre>import dask.array as da<br><br>dataset = da.ones((100000, 1000, 1000))</pre><p>Just by replacing numpy with dask.array, we are getting this as the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIXwVdG8SvXgx9eM45ZDzQ.png" /></figure><p>Wow!!! no errors. That&#39;s the power of dask.</p><p>By integrating with existing libraries dask enables developers and data scientists to transition from traditional single machine workflows to parallel and distributed computing without learning new frameworks or writing long and complex codes.</p><p>Let us try out one more example to understand Dask and parallel computation better.</p><p>let us run the following code.</p><pre>from time import sleep<br><br>def inc(x):<br>    sleep(1)<br>    return x+1<br><br>def add(x, y):<br>    sleep(1)<br>    return x+y</pre><p>just a normal python function with a delay of 1 second. Now, run the following to execute the functions.</p><pre>%%time #computes time taken to execute the code.<br><br>x = inc(1)<br>y = inc(2)<br>z = add(x, y)</pre><p>Well the output after execution of the above code is as follows</p><pre>CPU times: user 694 µs, sys: 47 µs, total: 741 µs<br>Wall time: 2 s</pre><p>In Jupyter Notebook it took around <strong>2 seconds</strong> to execute the above code. That is to increment 2 given numbers and then to add the 2 numbers.</p><p>now let us use the Dask Delayed decorator to check the parallel computation in python by wrapping the existing functions as shown:</p><pre>from time import sleep<br>from dask import delayed<br><br>@delayed<br>def inc(x):<br>    sleep(1)<br>    return x+1<br><br>@delayed<br>def add(x, y):<br>    sleep(1)<br>    return x+y</pre><p>Now we need to execute the below code to see the actual parallel computing in action.</p><pre>%%time<br><br># we wrap the delayed decorator and then pass in the inputs.<br>x = delayed(inc)(1)  <br>y = delayed(inc)(2)<br>z = delayed(add)(x, y)</pre><p>By executing the following code the output is as shown below:</p><pre>CPU times: user 848 µs, sys: 59 µs, total: 907 µs<br>Wall time: 3.97 ms</pre><p>hence with this, it is proved that dask is way faster in parallel computing.</p><p><strong>Note: That the above code was executed in 3.97 milliseconds (ms) not in seconds.</strong></p><h3>Conclusion</h3><p>In this article, we have seen about Dask and its parallel computing capability. We went through the concept of parallel computing and the implementation part where we implemented a simple python code to make us understand the importance of parallel computing and how easy Dask makes it for us to do it. I hope this article was useful to you all. Will see you in my next article until then as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4863838994ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/introduction-to-parallel-computing-in-python-using-dask-4863838994ae">Introduction to Parallel Computing in Python using Dask</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What in the World is Docker?]]></title>
            <link>https://medium.com/featurepreneur/what-in-the-world-is-docker-4327d1bb7250?source=rss-c4e35395b2b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4327d1bb7250</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hemanthhari2000]]></dc:creator>
            <pubDate>Tue, 30 Mar 2021 12:33:29 GMT</pubDate>
            <atom:updated>2021-03-30T12:33:29.795Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand the basics of Docker and its real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebZDQ3Ad_8WgDfh-QjivRA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ian Taylor</a> on <a href="https://unsplash.com/s/photos/container-ships?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Developing applications and deploying them in production is still a time-consuming and complex thing to do as a developer. We need to set all the dependencies, packages, libraries onto the server. The server may have some other OS and we need to build each dependency that is server-specific to run our application. Just by reading this, we get to know that this is a tedious process and requires a lot of time and energy just to set up the server to run our application. So, to avoid such work, <strong><em>Docker</em></strong> was released to ease the process. Docker uses a concept called <strong><em>Containerization,</em></strong> which makes the deployment process effortless.</p><h3>Overview</h3><p>Let’s take a look at the contents that we will cover in this article.</p><ul><li>Docker</li><li>Docker Images</li><li>Containers Vs Virtual Machines (VMs)</li><li>Installing Docker</li><li>Docker Commands</li><li>Implementation of Docker</li><li>Conclusion</li></ul><h3><strong>Docker</strong></h3><p>Docker is a set of Platform As A Service (PaaS) products that use OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries, and configuration files; they can communicate with each other through well-defined channels. Because all of the containers share the services of a single operating system kernel, they use fewer resources than virtual machines. The software that hosts these containers is called <strong><em>Docker Engine</em></strong>. Docker includes components such as <strong><em>Docker Client</em></strong>, <strong><em>Docker Server</em></strong>, <strong><em>Docker Machine</em></strong>, <strong><em>Docker Hub</em></strong>, <strong><em>Docker Composes,</em></strong> and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQPERZi0pkVNPfblez0UFQ.png" /></figure><p>Docker benefits both Developers and System Admins. It eradicates the machine-specific problem like <strong><em>“Code runs on one PC but not on the other”. </em></strong>Enterprises use Docker to securely built agile software delivery pipelines to ship new application features faster and more securely. It can not only be used for deployment but also for the development process, which makes it more scalable and robust.</p><h3>Docker Images</h3><p>A Docker image is a read-only template that contains a set of instructions for creating a container that can run on the Docker platform. It provides a convenient way to package up applications and preconfigured server environments, which you can use for your own private use or share publicly with other Docker users. You can pull some existing docker images from the official docker hub from <a href="http://hub.docker.com/"><strong><em>here</em></strong></a>.</p><p><strong><em>Note: You need to login into the docker hub account and then search for your images.</em></strong></p><h3>Containers Vs Virtual Machines (VMs)</h3><p><strong><em>Docker Containers</em></strong> are the lightweight alternatives of the virtual machine. It allows developers to package up the application with all its libraries and dependencies, and ship it as a single package. The best thing Docker offers you is you need not provide any space for storage or allocate any RAM for your application. It will automatically generate storage and space according to the application and its requirements. It does not require any hypervisor as the virtual machine does. Which makes it more scalable and fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snINBI0HUIYa0BWKyCO3Xg.jpeg" /></figure><p>Whereas a <strong><em>Virtual Machine</em></strong> is a virtual representation of a physical computer. They are referred to as guest machines that use our local hardware to function. <strong><em>Virtualization</em></strong> is the process of creating multiple virtual machines, each with its own operating system (OS) on a single physical machine. A VM cannot interact directly with a physical computer. Instead, it needs a lightweight software layer called a <strong><em>hypervisor</em></strong> to coordinate between it and the underlying physical hardware. The hypervisor allocates physical computing resources such as processors, memory, and storage to each VM. It keeps each VM separate from others so they don’t interfere with each other.</p><p>Let’s get our hands dirty as always and start implementing docker.</p><p><strong><em>Note: In this article, we use a Linux-based OS i.e, Ubuntu to run docker because it is easy and fast in Linux-based systems.</em></strong></p><h3><strong>Installing Docker</strong></h3><p>Now let us open our terminal and update your <strong><em>apt</em></strong> packages first using the following and install <strong><em>snap</em></strong> too.</p><pre>sudo apt update<br>sudo apt install snap</pre><p>That’s it for the prerequisite though. Now let’s install docker using <strong><em>snap.</em></strong></p><pre>sudo snap install docker</pre><p>Done. That’s right. We just installed docker in our Ubuntu. That was pretty easy, right?</p><h3>Docker Commands</h3><p>Now we’ll see some docker commands that will be useful in the long run.</p><p><strong>Note: make sure you use <em>sudo</em> before any docker command or else it won&#39;t execute in Ubuntu.</strong></p><ul><li>List Docker images</li></ul><pre>docker images</pre><ul><li>List all Docker running containers</li></ul><pre>docker ps -a</pre><ul><li>List Docker containers</li></ul><pre>docker container ls<br>docker container ls --all</pre><ul><li>Stop any Container</li></ul><pre>docker stop &lt;CONTAINER_NAME&gt;</pre><ul><li>Remove any Container</li></ul><pre>docker rm &lt;CONTAINER_NAME&gt;</pre><ul><li>Clear or Remove all Docker Containers</li></ul><pre>docker system prune -a</pre><p>for more such commands, visit the official <a href="https://docs.docker.com/engine/reference/commandline/docker/"><strong><em>Docker</em></strong></a> website.</p><h3>Implementation of Docker</h3><p>Go ahead and create your <strong><em>Dockerfile </em></strong>and pull the existing image from the Docker Hub. After pulling<strong><em> python image </em></strong>from Docker Hub go ahead and install <strong><em>NumPy</em></strong> or any other import you want. As this is an example of how Docker works so let us stick with simplicity here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQK4s0lOiK1ZkcXxFNIMDQ.png" /></figure><p><em>Dockerfile</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf08084d5f1a1d5a854a97af901f6731/href">https://medium.com/media/bf08084d5f1a1d5a854a97af901f6731/href</a></iframe><pre>FROM python:latest</pre><p>we import or pull the existing Python Docker Image from Docker Hub.</p><pre>ADD . /code<br>WORKDIR /code</pre><p>Add our existing working directory to the new directory <em>/code</em> inside the Docker Container.</p><pre>RUN pip install numpy</pre><p>Use the RUN command to run any terminal-specific commands like installing <em>numpy</em> using <em>pip.</em></p><pre>CMD [&quot;python&quot;, &quot;main.py&quot;]</pre><p>This CMD command is used to run the python command on the Docker terminal. Specify the command that is <strong><em>python </em></strong>to run any python file and the file itself to execute here it is <strong><em>main.py</em></strong></p><p>That’s it, our Docker is set and all we have to do now is create your main.py where you use some NumPy operation (as for this example) or any other operations of your choice.</p><p><em>main.py</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b71a46ff87c69c8d4e13e4ef8d5f775c/href">https://medium.com/media/b71a46ff87c69c8d4e13e4ef8d5f775c/href</a></iframe><p>Finally, build and run your Docker container using the following command</p><p><em>Build</em></p><pre>docker build -t docker-testing:latest .</pre><p><em>Run</em></p><pre>docker run -it docker-testing:latest sh</pre><p>That’s it. If your installing and setup was perfect then you should see output saying the following</p><pre>[[1 2 3 4 5]<br> [1 2 3 4 5]]</pre><pre>&lt;class &#39;numpy.ndarray&#39;&gt;</pre><p>Congratulations! you have successfully set up your docker station and now it is up to your applications to deploy using docker.</p><h3>Conclusion</h3><p>In this article, we have seen a detailed introduction about Docker and its uses in real-world applications. We understood the concept of containerization and also to demonstrate its functionality, we have implemented a simple Docker application. So, go ahead and discover new wonders with Docker. I hope this article was useful to you all. Will see you in my next article until then as always <strong>code learn repeat …….</strong></p><p>Follow for more…</p><ul><li><a href="https://github.com/Hemanthhari2000/">Hemanthhari2000 - Overview</a></li><li><a href="https://www.linkedin.com/in/hemanth-kumar-39697017a/">Hemanth Kumar - Developer/Research Intern at Tactii (formerly TalentAccurate) - Tactii (formerly TalentAccurate) | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4327d1bb7250" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/what-in-the-world-is-docker-4327d1bb7250">What in the World is Docker?</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>