Introduction to Flask: A beginner's guide to building web applications with Flask

Introduction to Flask: A beginner's guide to building web applications with Flask

ยท

4 min read

While starting with backend web development many folks have doubts about the technology that they should learn. They want something which is easy to understand and has a huge no. of use cases. If you are on the same path, So I want to introduce you all to Flask.

A micro web framework that is written in the Python programming language. It is easy to understand and simple than others and use to develop medium-sized web applications

Installation and Setup

To install Flask, Firstly you should have Python and pip(Pip Installs Packages) installed in your system which you can checkout by running the following command in your terminal :

python -v
pip -v

After that install Flask by running the command :

pip install flask

Now, you are all set to develop a Flask application. Let's create a main.py file to create a project :

touch main.py

Use your local editor and write these lines of code in your file :

from flask import Flask

app = Flask(__name__)

@app.route("/")
def Home():
    return "<p>Hello Flask!!</p>"

Here we import Flask into our application and then initialize our application in line app = Flask(__name__). Alright, Now We have to create some of the routes used to set routes to different web pages in the web application.

Now, we are all done with our minimal flask application which will render Hello Flask!!.

Run : python main.py or app.py to render your application in localhost:5000 ( default ).

Using Flask Extensions

One of the best things about Flask is that it has lots of different extensions available to do simple and efficient code. some of them are: gunicorn, Flask Mail, SQLAlchemy, Jinja Templating, Pytest and pytest-cov, Flask Liminter etc.

Jinja Templating and SQLAlchemy are the most common extensions used.

Jinja Templating

Jinja Templating is used to set up connections between Python files and HTML ( any text-based format ) files. As it is a template so, It uses variables and expressions to control the logic of the template. On rendering, These variables and expressions change into the values.

Under app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def Home():
    # variable example
    user = 'Flask'
    return render_template('index.html', name=user)

Under index.html

<html>
    <head>
        <title>Jinja Templating</title>
    </head>
    <body>
        <h3>Let's Learn {{ name }}</h3>
    </body>
</html>

It renders Let's Learn Flask.

Flask-SQLAlchemy

When it comes on connect the database with the Flask application, SQLAlchemy appears as the best choice. Flask-SQLAlchemy uses SQLAlchemy to provide ORM. ORM refers to Object-relational mapping.

Under app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/db'
db = SQLAlchemy(app)

# User class inherited from db.Model 
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

app.run(debug=True)

The above code sets up a Basic Flask application with a database connection and a model. Now, You can continue it building further based on backend logic and user experience.

Deploying Flask Application

Deployment of a Flask Application consists varieties of steps, we will go through each of them one by one -

  1. Purchasing a domain name - A domain name is super important to make applications live over to the internet. It is a costly process, but if you are a college and university student, you can utilize your college ID to get domain names for free. I will recommend Name.com. you can get it free from the GitHub Student Developer pack.

  2. Prepare Flask application for Deployment - In this step, you have to take a look our your application whether it is okay to go on the server or not. you can consider these points -

    • App Configuration

    • Production database setup

    • HTTPS server

  3. Hosting on Server - There are servers available like Apache, nginx, gunicorn etc. I am going for Gunicorn, which is a Python package that can be installed using pip.

     pip install gunicorn
    

    Alright, now you have to configure Gunicorn. you can do so either by Gunicorn command-line arguments or configuration file. At last, you have to set up a reverse proxy to route incoming requests to Gunicorn.

  4. Deploy on Hosting platform - Choose a hosting platform as per the requirements some of the popular hosting platform services are - Heroku, AWS, and DigitalOcean. now you can go with deployment documentation and take further steps like creating a new app instance, database setup and configuring environments variable.


Hope you love this article, Any suggestion or recommendation over to my writing knowledge. Feel free to deliever it to me. I am open for colloboration and discussion.

Thank you all ๐Ÿ’–

ย