How to Work with Ansible When and Other Conditionals

If you need to execute Ansible tasks based on different conditions, then you’re in for a treat. Ansible when and other conditionals lets you evaluate conditions, such as based on OS, or if one task is dependent on the previous task.

In this tutorial, you’re going to learn how to work with Ansible when and other conditionals so you can execute tasks without messing things up.

This Blog has been Written by Author of Automateinfra.com (Shanky) on adamtheautomator.com [ATA]

Click here and Continue reading

How to Install Terraform on Linux and Windows

Are you overwhelmed with the number of cloud services and resources you have to manage? Do you wonder what tool can help with these chores? Wonder no more and dive right in! This tutorial will teach how to install Terraform!

Terraform is the most popular automation tool to build, change and manage your cloud infrastructure effectively and quickly. So let’s get started!

This Blog has been Written by Author of Automateinfra.com (Shanky) on adamtheautomator.com [ATA]

Click here and Continue reading

The Ultimate Guide on Docker for Beginners [Easiest Way]

Table of Content

  • Introduction to docker
  • Why do you need Docker?
  • Docker Images
  • Docker Containers
  • Why Docker Containers not Hypervisor
  • Docker Client-Server Architecture

Introduction to docker

Docker is an open-source platform that allows you to deploy, run and ship applications. With Docker, it takes quick time to deploy, run and test your applications anywhere in different operating systems. It is a lightweight loosely isolated environment. It has a better cost-effective solution than hypervisors virtual machine as you can use more compute resources.

Docker is written in the Go programming language and takes advantage of several features of the Linux kernel to deliver its functionality.

Docker provides the ability to package and run an application in a loosely isolated environment called a container. Containers are lightweight and contain everything needed to run the application, so you do not need to rely on what is currently installed on the host.

Docker manages the lifecycle of containers starting from developing the applications using containers, which you can use or distribute later and deploy in any environment such as a local data center, a cloud provider, or a hybrid of the two.

Why do you need Docker?

Without Docker : As usual your Operating system are dependent on Hardware and are installed on it. But when you are hosting your applications directly on operating system then applications are dependent on different libraries and other compatible issues. So, when you have two or more applications it becomes difficult to manage so many micro services and takes long time to step up.

Without Docker

With Docker : As usual your Operating system are dependent on Hardware and are installed on it. Now this time you are hosting your applications on Docker rather than directly on operating system then applications have there own libraries and dependencies. So, when you have two or more applications it’s easier to manage as it has its own isolated environment.

With Docker

Docker Images

Docker images basically contain instructions for creating docker containers. Docker images are available in the public registry that is the docker hub and you can also customize the image by adding more instruction in a file which is known as the docker file.

Docker Images are binary data or package that contains application and all its software dependencies and runtimes.

Docker Images can be found on this link.

Docker Containers

Docker applications run inside a lightweight environment which is known as containers and you can run multiple containers in your host it could be windows, Linux, or macOS. Containers are runnable instances of an image. You can create, delete, stop, start containers at any point in time.

Containers are completely isolated environments . It can have its own services, networking interferences, processes, mounts etc. but they all share the same OS Kernel. For Example: the Ubuntu, Fedora, centos they all have same OS kernel i.e. Linux but have different software’s that why there are so many flavors of Linux available such as some are different in GUI or as command line.

OS kernel : OS kernel manages the operations of memory and CPU time. It is core component which acts as a bridge between applications or software’s and data processing performed at hardware level using system calls.

Docker container sharing the same kernel means: docker can run any containers on any operating system that are based and compatible on the underlying operating system kernel.

  • You cannot run Windows based container in the Linux based OS Kernel. For that you will require docker on windows.
  • You can run Linux based container in windows based OS kernel but actually you are using Linux virtual machine on top of windows and then running Linux based container on Linux virtual machine.
Different Operating system sharing the OS Kernel ( Linux )

In the below example: Docker can run any container based on Ubuntu, Fedora or Centos as the underlying OS kernel is ubuntu. So the Containers share all the networking and other OS things from kernel but only software is installed on container.

Why Docker Containers not Hypervisor

Docker containers has only 1 underlying operating system that helps in the cost optimization , utilization of resources , disk space and also helps in less time in booting.

With Hypervisor, you have so many operating system that increases the overload ( disk size) , utilization of resources and also takes more time to boot.

Normal OS – Virtualization – Containerization

There are two docker editions: community edition and the other is enterprise edition. The community edition is free and present in windows, Linux, macOS and cloud( AWS or Azure ) . Enterprise edition comes with more features such as image security, image management.

Docker Client-Server Architecture

Docker uses a client-server architecture where the docker client connects to the Docker daemon which performs all the functions such as building images, running containers, and distributing containers.

Docker client connects to docker daemon using REST API over Unix sockets. For example, when you run the docker run command your docker client first connects with docked daemon which performs the task. Docker daemons can also communicate with other daemons to manage containers.

Docker Daemon: dockerd is the docker daemon which listens to API requests and manages Docker objects such as images, containers, network, and volumes.

Docker registries store docker images. Docker hub is the public registry that anybody can use. Using docker pull or docker run command images are pulled from Docker hub and using docker push they are pushed into docker hub.

Docker commands

  • To run a container from nginx image.
    • If docker image is present on the system docker uses that to run the container else it will pull it from the docker hub and later for subsequent execution same image which got downloaded will be used.
    • By default container runs in Foreground or in attached mode that means container will be attached to the console or the standard out of the docker container and you will see the output of web service on your screen and you wont be able to do anything on the console. Press (Clt + C)to Exit
docker run name_of_the_image
docker run nginx
  • To run a container from ubuntu image. In this case container starts and exits immediately because unlike virtual machines docker are not suppose to host the operating system instead they are supposed to run either any web application or specific tasks or web server.
docker run ubuntu 
  • To run a container from ubuntu image and keep the container running you can allow container to sleep for particular time from an ubuntu image.
docker run ubuntu sleep 5000
  • To run a container from ubuntu image or centos image and keep the container running run the execute command on the container directly as shown below and followed by /cat/etc/*release* but container will exit after you log out from the container as it is not doing anything or running any service.
    • If application needs you to provide input then Dockerzing the application wouldn’t wait for the prompt it just prints the output on the standard output that is STDOUT because by default container doesn’t listhen to the standard input even though you are attached to the console. It doesn’t have terminal to read the input from.
    • You must map standard input of your host to the docker container using the i parameter.
    • With i parameter you have an interactive mode.
    • With t (sudo terminal) parameter you are attached to the container’s terminal. Because application prompts on the terminal and we haven’t attached to containers terminal.
docker run -it centos bash /cat/etc/*release*
  • To run a container in detached mode or in the background and you will get the prompt immediately as container starts. With this mode you need to use -d flag. The container will continue to run in the background.
docker run -d nginx
  • To attach the container back in attached mode.
docker attach name_of_the_container  or container_id
  • To list all the running container’s and some of the information about the containers.
docker ps
  • To list all the container ( Running, Pending, Inactive or terminated etc.)
docker ps -a
  • To stop a container. Stops the container but you don’t get rid of space consumption.
docker stop name_of_the_container
  • To remove the container and get rid of space consumption.
docker rm name_of_the_container
  • To remove multiple containers in the docker.
docker rm container_ID_1 container_ID_2 container_ID_3
  • To list all the docker images
docker images
  • To download or pull the docker image
docker pull name_of_the_image
  • To remove the docker images. Make sure first you get rid of all associated containers that is remove all the containers associated with the images.
docker rmi name_of_the_image
  • To execute a command inside a container
docker exec name_of_the_container cat /etc/host
  • To run a container from a specific version.
docker run image:tag
  • To access the application from web browser you would need to run the docker run command with p flag.
    • p flag will map Port 80 on docker host to Port 5000 to containers Port.
    • In Case 1 – Docker host will listen to application on port 80 on web and internally on Port 5000 on container IP address.
    • In Case 2 – Docker host will listen to application on port 8000 on web and internally on Port 5000 on container IP address.
    • In Case 3 – Docker host will listen to application on port 8001 on web and internally on Port 5000 on container IP address.
    • You can run as many applications you wish to run with different docker host ports but you cannot use the same docker host port again.
docker run -p 80:5000 nginx    # Case 1
docker run -p 8000:5000 nginx  # Case 2
docker run -p 8001:5000 nginx  # Case 3
  • To have a data persistent with the container you should consider mounting a volume from docker host to the container as when you run the MySQL container the volume is created on the /var/lib/mysql directory inside the container and is blown away as soon as you either stop or remove the container.
    • /opt/datadir is the volume created on docker host
    • /var/lib/mysql : Mapping the volume with containers directory
    • mysql is the name of the docker image
    • v flag mounts the volume from host to container.
docker run -v /opt/datadir:/var/lib/mysql mysql
  • To find detailed view of container use inspect command.
docker inspect name_of_the_container  or container_id
  • To find logs of the container use docker logs command.
docker logs container_name or container_id

Creating Your Own Docker Image

Why do you need to create your own docker image? As you might have seen the docker images are just the basic software applications or just the operating system but most of the times you need to create more and more software’s of top of the base image to modify your application. Lets checkout

To create your own Docker Image you need to have a file known as DockerFile where you define instructions that needs to be executed such as base image , update repository, Install dependencies, copy source code, Run the web application etc. Docker can build images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

Each instruction in DockerFile creates another layer that is (All the instructions takes their own memory). While building if any instruction fails and if you rebuild the image then previous instruction which are cached are used to build.

The build is run by the Docker daemon, not by the CLI. The first thing a build process does is send the entire context (recursively) to the daemon and daemon creates the new image.

docker build . 

To Build the docker Image using dockerfile on a different path use f flag.

docker build -f /path/to/a/Dockerfile .
  1. FROM : From instruction initializes new build stage and sets the base image for subsequent instructions. From instruction may appear multiple times in the DockerFile.
  2. ARG: ARG is the only instruction that comes before FROM and FROM takes the arguments.
  3. RUN: The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. RUN are declared with two ways either shell way or executable way.
    • Shell way: the command is run in a shell i.e. /bin/sh. If you need to run multiple command use backslash.
    • Executable way: RUN [“executable”, “param1”, “param2”] . If you need to use any other shell than /bin/sh than you should consider using executable way.
RUN 
/bin/bash -c 'source $HOME/.bashrc; \
echo $HOME'
RUN 

/bin/bash -c 'source $HOME/.bashrc; echo $HOME'
  1. CMD: The main purpose of a CMD is to execute the command within the container just like docker run exec command . CMD has also three forms as shown below. There can be only one CMD instruction in DockerFile. If you list more than one then last will take effect. Also if you don’t specify the executable in CMD then you can also use it along with ENTRYPOINT but make sure to define both CMD and ENTRYPOINT in json format.
    • CMD [“executable”,”param1″,”param2″]
    • CMD [“param1″,”param2”]
    • CMD command param1 param2

CMD defines default commands and/or parameters for a container. CMD is an instruction that is best to use if you need a default command which users can easily override

  1. ENTRYPOINT: An ENTRYPOINT allows you to run the commands as a executable in a container. When you provide the command line arguments to docker run it  will be appended all elements in an exec form ENTRYPOINT, and will override all elements specified using CMD. Lets look at an example.

ENTRYPOINT is preferred when you want to define a container with a specific executable. You cannot override an ENTRYPOINT when starting a container unless you add the --entrypoint flag.

Combine ENTRYPOINT with CMD if you need a container with a specified executable and a default parameter that can be modified easily

The Ultimate Guide on AWS Cloud Practitioner- PART-1

What does Server contains?

  • Compute: The Computation is done by CPU.
  • Memory : RAM is the memory of the machine.
  • Storage: Data
  • Database: Store Data in Structure way.

Why Cloud instead of Datacenter ?

  • You will need to pay rent for the data center.
  • You will need to Pay for maintenance , power supply , cooling and take care of data center.
  • Adding hardware and infrastructure takes more time.
  • Scaling is limited.
  • In case of disaster everything is lost.

Benefits of Cloud over Datacenter

  • Cloud computing is on demand delivery of compute power, database storage, applications and IT storage.
  • You pay as you use.
  • Provision exactly right type and size of compute resources and access instantly.
  • Simple way to access all services such as database , servers, storage.

Features of Cloud Computing

1. Cloud computing is flexible: If you need more services and more need of Servers you can easily scale up your cloud capacity or you may Scale down again.

2. Disaster Recovery – Cloud is helping organizations to move to that trend. With Allowing Automation and Creating Infrastructure with Different Automation Tools you can redeploy and rebuild your services ASAP. Also The Backups and format of recovery in Cloud is great.

3. Never Miss an Update: As The Service itself is not managed by organization, Provider takes care of your Infra and server Management so its Ideal solution than the reality.

4. Cloud services minimizes cloud Expenditure: Cloud Computing cuts Hardware costs. You simply pay a you go and Enjoy the services.

5. Workstations in the cloud: You can work from anywhere in the world and anytime.

6. Cloud computing offers security: Lost Laptops are Billion dollar Business problem but loss of expensive piece of data is exceptionally a big Problem. Here your data resides in Cloud with more Max security and tolerance which is a greatest advantage in my Option.

7. Mobility: Cloud computing allows mobile access to corporate data via smartphones and devices, which is a great way to ensure that no one is ever left out of the loop.

Cloud computing adoption is on the rise every year, and it doesn’t take long to see why enterprises recognize cloud computing benefits.

Different Types of Cloud Computing

SAAS (Software as a Service): With SaaS, an organization accesses a specific software application hosted on a remote server and managed by a third-party provider

PAAS (Platform as a Service): With PaaS, an organization accesses a pre-defined environment for software development that can be used to build, test, and run applications. This means that developers don’t need to start from scratch when creating apps.

IAAS (Infrastructure as a Service): With IaaS, an organization migrates its hardware—renting servers and data storage in the cloud rather than purchasing and maintaining its own infrastructure. IaaS provides an organization with the same technologies and capabilities as a traditional data center, including full control over server instances.

System administrators within the business are responsible for managing aspects such as databases, applications, runtime, security, etc., while the cloud provider manages the servers, hard drives, networking, storage, etc.

How to run Python flask applications on Docker Engine

Cannot we isolate our apps so that they are independent of each other and run perfectly ? The answer is absolutely “YES”, that correct that’s very much possible with docker and containers. They provide you isolated environment and are your friend for deploying many applications with each taking its own container. You can run as many as containers in docker and are independent of each other. They all share same kernel memory.

In this tutorial we will go through a simple demonstration of a python application which will run on docker engine.

Table of content

  1. What is Python ?
  2. What is docker ?
  3. Prerequisites
  4. Create a Python flask application
  5. Create a Docker file
  6. Build Docker Image
  7. Run the Python flask application Container
  8. Conclusion

What is Python ?

Python is a language from which you create web applications and system scripts. It is a used vastly across the organizations and very easy to learn. Python apps require isolated environment to run its application very well. This is quite possible with Docker and containers which we will use in this tutorial.

If you wish to know more about python please visit our Python’s Page to learn all about Python.

What is docker ?

Docker is an open source tool for developing , shipping and running applications. It has ability to run applications in loosely isolated environment using containers. Docker is an application which helps in management of containers in a very smooth and effective way. In containers you can isolate your applications. Docker is quite similar to virtual machine but it is light weighted and can be ported easily.

Containers are light weighted as they are independent of hypervisors load and configuration. They directly connect with machines ie. hosts kernel.

Prerequisites

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

Create a Python flask application

  • Before we create our first program using python flask we need to install python flask and python virtual environment for flask to run.

pip install virtualenv # virtual python environment 
  • Create and activate a virtual environment named virt:
virtualenv venv
source virt/bin/activate
 
  • Finally install Flask

pip install flask # Install Flask from pip
  • Now create a text file and name it as app.py where we will write our first python flask code as below.
from flask import Flask # Importing the class flask

app = Flask(__name__)   # Creating the Flask class object.

@app.route('/')         # app.route informs flask about the URL to be used by function
def func():             # Creating a function
      return("Iam from Automateinfra.com")  

if __name__ ==  "__main__":    # Programs starts from here.
    app.run(debug=True)
  • Create one more file in same directory and name it as requirements.txt where we will define the dependency of flask application
Flask==1.1.1
  • Now our python code app.py and requirements.txt are ready for execution. Lets execute our code using below command.
python app.py
This image has an empty alt attribute; its file name is image-42.png
  • Great, so our python flask application ran successfully on our local machine. Now we need to execute same code on docker . Lets now move to docker part.

Create a docker file

Docker file is used to create a customized docker images on top of basic docker image. It is a text file that contains all the commands to build or assemble a new docker image. Using docker build command we can create new customized docker images . Its basically another layer which sits on top of docker image. Using newly built docker image we can run containers in similar way.

This image has an empty alt attribute; its file name is image-43.png
  • Create a docker file and name it as Docker file . Keep this file also in same directory as app.py and requirements.txt
FROM python:3.8           # Sets the base image 
WORKDIR /code             # Sets the working directory in the container
COPY requirements.txt .   # copy the dependencies file to the working directory
RUN pip install -r requirements.txt  # Install dependencies
COPY src/ .               # Copy the content of the local src directory to the working directory
CMD [ "python", "./app.py" ] # Command to run on container start  
This image has an empty alt attribute; its file name is image-44.png

Build docker Image

  • Now we are ready to build our new image . So lets build our image
docker build -t myimage .
  • You should see the docker images by now.
docker images
This image has an empty alt attribute; its file name is image-45.png

Run the Python flask application Container

  • Now run our first container using same docker image ( myimage)
docker run -d -p 5000:5000 myimage
  • Verify if container is successfully created.
docker ps -a
This image has an empty alt attribute; its file name is image-45.png

Conclusion

In this tutorial we covered what is docker , what is python and using python flask application created a application on docker engine in one of the containers.

Hope this tutorial will helps you in understanding and setting up Python flask and python flask applications on docker engine in ubuntu machine.

Please share with your friends.

What is Python Flask and how to work with Python Flask

There are various web frameworks in market to create and build from simple to coolest applications using Python and one of them is Flask. In this tutorial you will learn what is Python Flask and how to work with Python Flask.

Table of Contents

  1. What is Web Framework?
  2. Why do we need Virtual Environment for Python?
  3. Prerequisites
  4. Installing and Setting up Python Flask on your machine
  5. Working with Python Flask (URL binding, URL redirection and debug mode)
  6. Working with Python Flask (HTTP METHOD: Rendering Templates /HTML PAGE)
  7. Working with Python Flask (HTTP METHOD: Rendering Templates and redirecting html page)
  8. Working with Python Flask (File Uploading)
  9. Conclusion

What is Web Framework?

The Simple answer is Framework is Code library which makes life of developer easy by reusing the code , extensions for operation to build a reliable , scalable and maintainable web apps. There are different Python Web frameworks such as FLASK , TORNADO, PYRAMID and DJANGO .

Why do we need Virtual Environment for Python?

When we create projects for Python we are dependent on several libraries and dependencies , so in order to work on particular project with specific versions of libraries and package it is recommended and a better approach to have separate virtual environment else applications with same libraries and version it may be break the functionalities.

Prerequisites

This post will be a step-by-step tutorial. If you’d like to follow along, ensure you have the following in place:

  • Python v3.6 or later – This tutorial will be using Python v3.9.2 on a Windows 10 machine. In case you don’t have Python installed then install it from here.
  • A code editor – This tutorial will use Visual Studio (VS) Code.

Installing and Setting up Python Flask on your machine

Now , you have idea to some extent about the Python Flask that is it is a web framework for Python. Next, let us work with it using some basic code and programs. Lets begin !

  • Assuming you are on your favorite code editor such as Visual Studio.
  • Before you write first python application on flask make sure you have virtual environment installed on your system. Python 3 comes with a virtual environment module called venv preinstalled so we will skip this step.
  • Next, create a environment named virt on your machine using below commands. This is different from the virtual environment.

py -3 -m venv virt
  • Now, Activate a virtual environment
  • Finally, Now Install Python flask on your machine by running the following command.
pip install flask # Install Flask from pip

Below distributions will be installed automatically when installing Flask.

  • Werkzeug implements WSGI, the standard Python interface between applications and servers.
  • Jinja is a template language that renders the pages your application serves.
  • MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks.

Lets learn few code components inside Python flask that are very important for flask developers.

  • app.route(rule, options)
    • The rule parameter represents URL binding with the function.
    • The options is a list of parameters to be forwarded to the underlying Rule object.
  • app.run(host, port, debug, options)
    • Host : (Default) 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally.
    • port : Defaults to 5000.
    • debug: Defaults to false. If set to true, provides a debug information.
    • options: To be forwarded to underlying server.

Working with Python Flask (URL binding, URL redirection and debug mode)

Lets learn how to work with URL binding, URL redirection and debug mode in python flask program.

  • Assuming you are still on code editor.
  • Create a folder on the visual studio code and name it as Flask and under that create a file such as flask.py
# CREATE A FLASK APPLICATION

from flask import Flask, url_for # Importing the class flask 
from markupsafe import escape

# Creating Flask class object/instance. The first argument is name of application’s module or package
app = Flask(__name__) 

# route() tell Flask what URL should trigger our function.
@app.route('/home') 
def home():
    return "This is my First Flask Website but Actually, I own Automateinfra.com"
@app.route('/login')
def login():
    return "This is my login page"
@app.route('/user/<username>') # Function receives <variable_name> as a keyword argument
def profile(username):
    return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def post_id(post_id):
    return 'Post %d' % post_id

# To build a URL to a specific function, use the url_for() function.
with app.test_request_context(): 
    print(url_for('home'))
    print(url_for('login'))
    print(url_for('profile', username = 'Automate Infra'))
    print(url_for('post_id', post_id = '100'))

if __name__ =='__main__':
    app.run(debug=True)
  • Execute the flask program by running the command on visual studio terminal as below.
python flask.py
O/P on Visual Studio Code Terminal:

* Serving Flask app "application2" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
/home
/login
/user/Automate%20Infra
/post/100
 * Debugger is active!
 * Debugger PIN: 285-837-988
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Working with Python Flask (HTTP METHOD: Rendering Templates /HTML PAGE)

Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the Jinja template library to render templates.

  • Assuming you are still on code editor. Create one folder templates and under that create another file hello.html and paste the below content.
# THIS IS MY HTML FILE WHICH IS BEING USED IN FLASK APP BELOW

<!DOCTYPE html>

<title>Hello Welcome</title>
{% if name %}
<h1>Hello {{name}} , Welcome </h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
  • Create a one more file and name it as application.py and paste the below content.
from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')

def hello(name=None):
    return render_template('hello.html', name=name)

if __name__ =='__main__':
   app.run(debug=True)

Your folder structure should like below.

  • Execute the flask program by running the command on visual studio terminal as below.
python render_html.py
  • Navigate to the browser and open 127.0.0.1:5000/hello and 127.0.0.1:5000/hello/<name> and you should see the output as below.

Working with Python Flask (HTTP METHOD: Rendering Templates and redirecting html page)

Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.

  • Assuming you are still on code editor. Create another file code.html and paste the below content.
# This is my HTML Page

<html>
  <body>
    <form action="http://localhost:5000/login" method="post">
      <p>Please Enter your name</p>
      <p><input type="text" name="automateinfra" /></p>
      <p><input type="submit" value="Submit" /></p>
    </form>
  </body>
</html>

  • Create a one more file and name it as render_redirection_html.py and paste the below content.
  • # MY FLASK APPLICATION 
    
    from flask import Flask , redirect , url_for , request
    app = Flask(__name__)
    
    @app.route('/success/<name>')
    def success(name):
        return 'welcome %s' % name
    
    @app.route('/login', methods = ['GET','POST'])
    def login():
        if request.method == 'POST':
           user = request.form['automateinfra']
           return redirect(url_for('success', name = user)) 
        else:
           return "INVALID"
      
    if __name__ == '__main__':
       app.run(debug = True)
    • Now execute the python program by running the following command.
    python render_redirection_html.py
    • Simultaneously run html page which you created in any browser and provide the name as automateinfra

    As soon as you Submit the form see the response as below in Python Terminal as below.

    
    
    * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 285-837-988
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    127.0.0.1 - - [16/Jan/2021 23:28:38] "POST /login HTTP/1.1" 302 -
    127.0.0.1 - - [16/Jan/2021 23:28:38] "GET /success/Automate%20infra HTTP/1.1" 200 -
    

    On browser, you will notice that when form is submitted it gets redirected to the Flask application.

    Working with Python Flask (File Uploading)

    Let’s start with a very basic application that uploads a file to a specific upload folder and displays a file to the user.

  • Assuming you are still on code editor. Create another file upload.html and paste the below content.
  • <html>
       <body>
          <form action = "http://localhost:5000/success" method = "POST" 
             enctype = "multipart/form-data">
             <input type = "file" name = "file" />
             <input type = "submit"/>
          </form>   
       </body>
    </html>

  • Create a one more file and name it as file_upload.py and paste the below content.
  • from flask import *  
    app = Flask(__name__)  
     
    @app.route('/upload')  
    def upload():  
        return render_template('upload.html')  
     
    @app.route('/success', methods = ['POST'])  
    def success():  
        if request.method == 'POST':  
            f = request.files['file']  
            f.save(f.filename)  
            return render_template('success.html', name = f.filename)  
      
    if __name__ == '__main__':  
        app.run(debug = True) 
    • Now, execute the python script using below command
    python file_upload.py
    • Now click on Submit.

    Conclusion

    In this tutorial you learnt what is Python flask and how to install flask on your windows machine. Finally you learnt how to work with Python flask such as URL binding, URL redirection and debug mode , Rendering Templates and redirecting html page and file uploading.

    Hope this tutorial was helpful and please share if you like it.