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.

Python Flask Tutorial: All about Python flask

If you are looking to create Python applications or programs that allow you to work with various API requests, nothing could be better than one of the most widely used web frameworks, Python flask.

With Python flask web frameworks, you can create and build from static to dynamic applications and work with API requests.

In this Python flask tutorial, you will learn everything you should know about Python flask, such as installing flask, flask render_template, etc.

Join 28 other followers

Table of Content

  1. What are Web Frameworks?
  2. What is Python Flask?
  3. What is WSGI (Web Server Gateway Interface)?
  4. Why do we need Virtual Environment for Python?
  5. Prerequisites
  6. Installing and Setting up Python Flask on your machine
  7. URL binding, URL redirection with flask url_for in Python Flask
  8. Rendering templates or html page using flask render_template
  9. Rendering templates and redirecting html page using flask render_template
  10. flask file upload: Easy Example
  11. Conclusion

What are Web Frameworks?

The web frameworks or web application frameworks are the software framework designed to support the development of web applications, including web services, web resources, and web APIs.

Some of the most popular web frameworks are React.js, Angular, Tornado, PYRAMID, DJANGO, and one of the best Python flask.

There is a difference between web frameworks and library. Library is a set of resuable functions that you call and in contrast frameworks contains code which aids in programming rather you calling it.

What is Python Flask

Python Web frameworks contain a collection of packages or modules that allow developers to write Web applications or services easily in Python code.

To run the application in the Python Flask framework, First, you need to import the Flask class. An instance of this class will be our WSGI application. While Python flask is lightweight and easy to use but Flask’s built-in server is not suitable for production as it doesn’t scale well.

Some of the options available for properly running Flask in production are Deploying Flask on Heroku, Deploying Flask on Google App Engine, Deploying Flask on Google Cloud Run, Deploying Flask on AWS Elastic Beanstalk, Deploying on Azure (IIS),Deploying on PythonAnywhere etc.

What is WSGI (Web Server Gateway Interface)?

WSGI stands for “Web Server Gateway Interface,” which is used to forward requests from a web server (such as Apache or NGINX) to a backend Python web application or framework. Responses are then passed back to the webserver to reply to the requestor.

WSGI container is altogether a separate running process that runs on a different port than your web server, and your web server is configured to pass requests to the WSGI container which runs your web application, then pass the response (in the form of HTML) back to the requester on the browser.

A web server’s configuration specifies what requests should be passed to the WSGI server to process. Once a request is processed and generated by the WSGI server, the response is passed back through the web server and the browser.

WSGI working
WSGI working

Why do we need Virtual Environment for Python?

When we create projects for Python, you are dependent on several libraries and dependencies, so to work on a particular project with specific versions of libraries and packages, it is recommended and a better approach to have a separate virtual environment else applications with the same libraries and version it may be breaking 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:

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

Installing Python Virtual Enviornment and Python Flask on Windows

Now, you just learned about Python Flask that is it is a web framework for Python. Next, let’s kick off this tutorial by installing and setting Python Flask on your machine; our work with it uses some basic code and programs. Let’s begin!

  • Before you write your first python flask application make sure you have virtual environment installed and created on your system.

Python 3 comes with a virtual environment module called venv preinstalled so we will skip this step.

  • Now, install the virtual enviornment using the below command. They essentially allow you to create a “virtual” isolated Python installation and install packages into that virtual installation
py -m pip install --user virtualenv
  • Next, you need to use the venv module command to create a virtual environment. The name of the virtual enviornment is virt. This command will also create the directory with the same name(virt), a file inside it named pyvenv.cfg and a script folder containing Python binaries as shown below.

To create a virtual environment, go to your project’s directory and run venv. If you are using Python 2, replace venv with virtualenv in the below commands.

py -3 -m venv virt    # virt is the location to create the virtual environment
creating a virtual environment
creating a virtual environment
Generated pyvenv.cfg with virtual environment command
Generated pyvenv.cfg with virtual environment command
  • Before you can start installing or using packages in your virtual environment, you’ll need to activate it. Activating a virtual environment will put the virtual environment-specific python and pip executables into your shell’s PATH
activating the virtual enviornment
activating the virtual environment

To activate the virtual enviornment in ubuntu or Linux machine use (source virt/bin/activate) command.

  • Finally, install a Python flask on your machine by running the following command. After executing the command below, distributions and dependencies are 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.
pip install flask # Install Flask from pip
Installing Python flask
Installing Python flask

URL binding, URL redirection with flask url_for in Python Flask

Now that you have a Python flask installed on your machine and setup, it is not useful unless you use it. Eager to get started? This section gives a good introduction to flask application.

In the python flask program, let’s learn how to work with URL binding, URL redirection, and debug mode.

  • Open your favorite code editor such as visual studio, and create a folder named Flask and create a file flask_prog.py inside it and copy-paste the below code.
    • app = Flask(__name__) : An instance or object of the class will be our WSGI application and acts as a central registry for the view functions, the URL rules, template configuration, and much more.__name__ is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files.
    • app.route(rule, options)
      • The rule parameter represents URL binding with the function.
      • The options list 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; you can set it to 5001, 5002, etc.
      • Debug Defaults to false. If set to true, it provides debug information.
      • options: To be forwarded to the underlying server.
# CREATE A FLASK APPLICATION

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

# Creating Flask class object/instance named app, The first argument is name of application’s module or package. It will also work with __name__
# app = Flask(__name__.split('.')[0])  #  This is a comment to show how to add a argument name  
app = Flask(__name__) 

# route() tell Flask what URL should trigger our function.
#  route() decorator to 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)

  • Now execute the flask program by running the following command on the visual studio terminal.
python flask_prog.py
Executing the flask python program
Executing the flask python program

To ignore the WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.

export FLASK_APP=flask_prog
export FLASK_ENV=development
flask run
Running Python application
Running Python application

To verify the application working, navigate to the browser and hit 127.0.0.1:5000/login or 127.0.0.1:5000/user/<any-username>

Checking flask app
Checking flask app
Checking the user login screen
Checking the user login screen

Rendering templates or html page using flask render_template

One of the coolest features of Python is to use of templates. Templates are files containing static data and 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. Let’s dive in.

Assuming you are still on code editor.

  • Create one folder named 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 one more file and name app.py under the Flask folder 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)
  • Now, you should have a folder structure something like the below.
tree structure of flask application
the tree structure of flask application
  • Finally, execute the flask program by running the Python command on the visual studio terminal, as shown below.
python app.py
Running flask application and generating GET and POST requests
Running flask application and generating GET and POST requests
  • 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 below.
checking the app locally on /hello URL
checking the app locally on /hello URL
checking the app locally on /hello/username URL
checking the app locally on /hello/username URL

Rendering templates and redirecting html page using flask render_template

Web applications use different HTTP methods when accessing URLs. 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>
Opening the HTML form
Opening the HTML form
  • Create another file redirection.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 redirection.py
Running the flask app
Running the flask app.
  • Simultaneously run html page (code.html) in any browser and provide the name as automateinfra
Submitting the form
Submitting the form

On browserYou will notice that when the form is submitted, it gets redirected to the Flask application and execute the success function.

Getting the same output with the specified name
Getting the same output with the specified name

flask file upload: Easy Example

You have learned how to render web pages and HTML pages by now. Now, lets us dive into the file uploading site and learn how to upload the file within a specific folder and display a file to the user. Are you interested in seeing an example of a flask file upload? If yes? Let’s dive in.

  • Create a 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 another file upload_flask.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 the below command
python upload_flask.py
Executing the flask application to upload the file
Executing the flask application to upload the file
Uploading the file in HTML form
Uploading the file in HTML form
  • Now click on Submit.
File uploaded successfully
File uploaded successfully

Join 28 other followers

Conclusion

This tutorial taught you what Python flask is and how to install a flask on your windows machine.

Also, you learned how to work with Python flask, such as URL binding, URL redirection and debug mode, Rendering Templates, and redirecting html page and file uploading.

So which applications are you launching next on the Python flask web framework?