Getting started with Flask

Syed Ibrahim Hussain
6 min readNov 2, 2020

--

Flask is Python’s most popular web application framework. It was developed by Armin Ronacher. Flask helps in establishing a strong foundation for a full-stack web applications. At the end of this post, you will gain enough knowledge about flask and to be able to create a basic web application. So, let’s start!

What is Flask?

Flask is a light-weight, modular, server-side Python framework that allows you to develop web applications. Compared to the extensive full-stack frameworks available Flask is an excellent choice for building smaller applications, APIs, and web services. Flask is a micro-framework that is compact, easy to understand and the perfect go-to for beginners.

Flask provides a library of modules and functions which helps you to create backend systems for the web applications. It also helps to create custom endpoints that server respond to the requests from the front-end of the website without having to worry about the lower-level implementations of thread management, data transfer protocols, etc. Flask allows you to get a web server running in few lines of code with hardly any dependencies and project layouts.

Among the many web application frameworks available for Python ( Django, Flask, Web2py, TurboGears, Bottle, CherryPy, Falcon, Tornado, Pyramid, Masoniteetc), Flask and Django are the most popular ones. Both are used extensively by the Python community for building applications ranging from small scale pet projects to more complex web apps for the masses.

List of companies using Flask in web development:

  • reddit.
  • Lyft.
  • trivago.
  • HENNGE K.K.
  • CRED.

Flask Installation in Python.

1) Setting up the virtual environment.

To set up the environment, we’ll create a virtual environment using virtualenv and then install Flask using Python’s PIP package manager. It is a good practice to use a virtual environment as it keeps your project dependencies cleanly managed, separated from other project dependencies and segregated from the global Python modules.

Step 1: Installing virtualenv (optional) –

To install a virtual environment, run the following command from the command line.

python3 -m pip install virtualenv

Step 2: Creating a new directory for this tutorial –

Navigate to the desired location/directory using command line where you wish to create a new tutorial directory and follow the commands of step 2.

mkdir flask-tutorialcd flask-tutorial

Step 3: Creating a virtual environment–

In this step we are creating a virtual environment in the current directory (i.e. flask-tutorial). We need to provide a name for the new virtual environment. I am going to call it venv, you are free to name it anything else. In order to create to a virtual environment run the command of step 3. After the execution of the command a directory named venv will be created in flask-tutorial directory.

Virtualenv venv

Step 4: Activating virtual environment–

After creating the virtual environment we need to activate it. If you are on a Windows machine run the following command to activate it.

venv\scripts\activate

You will see (venv) on the left side of the prompt of your command line, which indicates that you are inside a virtual environment.

When you need to go back to the original/default environment provided by your system, just run the following command:

deactivat

2) Installing Flask

Now that your virtual environment is ready, let’s install Flask. Run the following command to install Flask in the environment:

python3 -m pip install Flask

It will install all the dependency along with Flask for you.

Creating Flask application

In your flask-tutorial directory, create a file named “app.py” for editing in your favorite text editor:

# app.pyfrom flask import Flaskapp = Flask(__name__)# defining a route@app.route("/") # decoratordef Home(): # route handler function# returning a responsereturn "Hello World!"if __name__=="__main__":
app.run(debug = True)

Use the following command to run the application.

python3 -m flask run

or

flask run

You can see that the server is running on port 5000 of your localhost. This means everything is working. Copy the localhost URL i.e. http://127.0.0.1:5000/ and paste it in your browser to check the output of the code.

Output:

Hurry!!! we have successfully created our first Flask application.

Rendering HTML content.

Browsers can parse HTML content returned as a string from the server. The string message returned in the below code will be rendered as HTML content by the browser.

# app.pyfrom flask import Flaskapp = Flask(__name__)# home route@app.route("/")def hello():# returning stringreturn "<html>\<body>\<h3><u>Hello John!</u></h3>\</body>\</html>"
if __name__=="__main__":
app.run(debug = True)

Output:

Real world webpages encompasses different programming languages such as HTML, CSS, JavaScript, etc. for different purposes. The above method of returning webpages in the form of strings would be an inappropriate and unrealistic way for any webpage. The solution to this problem is to store HTML templates in separate files and use them for rendering web pages, for which we can use Flask’s render_template() function.

Use of render_template() function

The render_template() function takes the name of the HTML file as an argument. It looks for the file mentioned in the argument in the directory called ‘template’. Now we have to create a directory by the name ‘templates’ in the parent directory i.e. flask-tutorial. In template directory create a index.html file and write the HTML code.

<!-- /templates/index.html --><html><body><h3><u>Hello World!</u></h3></body></html>-------------------------------------------------------------------
# app.py
from flask import Flask, render_template # importing the render_template functionapp = Flask(__name__)# home route@app.route("/")def hello():return render_template('index.html')
if __name__=="__main__":
app.run(debug = True)

Output:

we can also pass the data from the server to HTML template with the help of jinja2 template engine which is used by Flask. Data can be passed as an argument of render_template() function.

from flask import Flask, render_template
app = Flask(__name__)
# home route@app.route("/")def hello():return render_template('index.html', name = 'John', age='15') # sending a data to the template
if __name__=="__main__":
app.run(debug = True)

We can receive the data by printing it using the operator {{ }}.

<!-- /templates/index.html --><!DOCTYPE html><html><body><!-- name variable populated before rendering--><h3><u>{{name}} is {{age}} years old.</u></h3></body>
</html>

Output:

Conclusion.

In this post, we learned about Python’s most popular web application micro-framework, Flask. We set up a virtual environment, installed the package, and learned how to create a basic web application using flask. Now that you have all the information go ahead and build something — a personal portfolio, a website of your startup and test your knowledge by doing it yourself.

--

--

No responses yet