How to Create a Your First Flask Application in 5 Minutes

How to Create a Your First Flask Application in 5 Minutes

In this post, we discuss how to create a Flask "Hello, world" and list application to get you up and going with this popular Python framework.

Create a Flask Application in a Few Minutes. In this post, we discuss how to create a Flask "Hello, world" and list application to get you up and going with this popular Python framework.

According to The Pallets Projects, Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy. This article will even make it easier by showing a step-by-step guide to creating a Python Flask web application with auto-generated desired data to get the application started.

To start, let's create a simple "hello world" application. First, create a new project. From the terminal or command line create a new directory: 

mkdir myproject
cd myproject

Inside the project directory, create a virtual environment for the project. You can check virtualenv for more information. First, install virtualenv, create one, activate it, and install Flask:

pip install virtualenv
#Create virtualenv
python3 -m venv venv
#Create virtualenv for windows
py -3 -m venv venv
#Activate virualenv:
. venv/bin/activate
#Activate virualenv for windows
venv\Scripts\activate
#Install Flask on the enviroment
pip install flask

The project setup is now ready to start adding functionalities. To start, let's create a new file in the same directory with the following content and name it main.py.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World!"

We can now run the application by telling the terminal which application to run by using the following commands: 

#Tell the terminal what application to run
export FLASK_APP=main.py
#Tell the terminal what application to run for windows
set FLASK_APP=main.py
#Run the application
flask run

The result should be like the following, telling you that the application is running on http://127.0.0.1:5000/. Navigating to this page should return "Hello World."

This is image title

Hello, world output

After completing the first part of the article, let's move to the next part and add functionality to our project. To start, we will download SQLALCHEMY to our project, which is an open source SQL toolkit and object-relational mapper for Python. We will download some other packages for Flask, such as wtforms and flask-wtforms to build our forms.

#To install Flask-SQLAlchemy
pip install pip install flask-sqlalchemy
#To install WTForms
pip install WTForms
#To install Flask-wtforms
pip install Flask-WTF

It's recommended to add the installed packages to a requirements format file. To do so, run the following command:

pip freeze requirements.txt

This command will generate a file called requirements.txt. It's used to store the packages, you can use the following command to install the packages from the requirements file. (this step may be skipped if you are running the code on the same machine used for the previous steps.)

pip install -r requirements.txt

After having the project ready for the new functionalities, let's add some magic to it. To start, let me quickly introduce the Clowiz CodeGen feature from The Cloud Wizard.

The following image represents the CodeGen feature and all its components:

This is image title

Project components

To start adding magic to the project:

  1. Go to https://www.clowiz.com/code-generator/ to start using the CodeGen feature.

  2. From the technologies section press on the Python Flask logo.

  3. In the metadata section, fill in the Form Name (e.g. Employee). (It can be anything you like.)

  4. In the Field Name section, change the first value to e.g. Name.

  5. The second one can be renamed to Email. (Change the Data Type to Email.)

  6. The third one can be changed to Salary and the Data Type can be changed to Double.

  7. Copy the code from the generated code section into our main.py file below the hello() method.

Now, let's define the database model, back to Clowiz AppGen, choose SQLAlchemy Model from the Generators section and copy the generated code and paste it in the  main.py  file under the form that we created.

After saving the main.py file, go to the terminal and execute the following commands to create the database:

python3
from main import db
db.create_all()

The next step is to create the routes for the application back to Clowiz AppGen. Then, choose from the generators view, copy the generated code, paste it below the database model in the main.py file, and save it.

Your main.py file should look like the following:

from flask import Flask, escape, request

app = Flask(__name__)

app.config['SECRET_KEY'] = 'any secret key'

@app.route('/')
def hello():
    return "Hello World!"

from flask_wtf import FlaskForm
from wtforms import SubmitField, HiddenField, StringField, IntegerField, DecimalField
from wtforms.validators import Email

class EmployeeForm(FlaskForm):
    id = HiddenField()
    name = StringField('Name')
    email = StringField('Email', validators=[Email()])
    salary = DecimalField('Salary')
    submit = SubmitField("Save")

from flask_sqlalchemy import SQLAlchemy
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/employee.db"
db = SQLAlchemy(app)

class Employee(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    email = db.Column(db.String)
    salary = db.Column(db.Numeric)
    references = db.Column(db.String)

    def __repr__(self):
        return "(%r, %r, %r)" %(self.name,self.email,self.salary)

from flask import render_template, request, flash, redirect, url_for

@app.route("/employee", methods=["GET", "POST"])
def createEmployee():
    form = EmployeeForm(request.form)
    employees = Employee.query.all()
    if form.validate_on_submit():
        employee = Employee(name=form.name.data, email=form.email.data, salary=form.salary.data)
        db.session.add(employee)
        db.session.commit()
        db.session.refresh(employee)
        db.session.commit()
        flash("Added Employee Successfully")
        return redirect(url_for("createEmployee"))
    return render_template("employee.html", title="Employee", form=form, employees=employees)

@app.route("/updateEmployee/", methods=["GET", "POST"])
def updateEmployee(employee_id):
    employee = Employee.query.get(employee_id)
    form = EmployeeForm(request.form, obj=employee)
    if form.validate_on_submit():
        form.populate_obj(employee)
        db.session.commit()
        flash("Updated Employee Successfully")
        return redirect(url_for("createEmployee"))
    return render_template("employee.html", title="Employee", form=form, employees=Employee.query.all())

@app.route("/deleteEmployee/", methods=["GET", "POST"])
def deleteEmployee(employee_id):
    employee = Employee.query.get(employee_id)
    db.session.delete(employee)
    db.session.commit()
    return redirect(url_for("createEmployee"))

Since we have a created a view, we should present the form to the user. Let's see how to generate the user interface.

Create a new directory in the project directory called templates by using the following commands(this folder must be called templates):

  1. In the folder, create two files, one called layout.html (note, this must be called layout.html because it will be imported in the employee.html file), and one called employee.html.
mkdir templates
touch templates/layout.html
touch templates/employee.html

3. Go back to Clowiz AppGen, choose Layout from the Generators section, copy the generated code, and paste it in the layout.html file.

4. Change the Generators section to Template and copy the generated code to the employee.html file.

5. Save the files and run flask run in the terminal. Then, navigate to .

You should see the following and be able to add a new record.

This is image title

Adding a new employee

Now fill in the form and save the values you will get the following:

This is image title

Employee successfully added

You can even update the record by pressing on the update button, changing the value you wish to update, and saving it.

This is image title

New employee displayed

To delete a record, press on the delete button.

You can get all the above steps with a better project structure and production-ready docker build ready for you by clicking the Download As Full Project button at the bottom of the CodeGen page.

Summary

In this post, we have created a simple "Hello, world" app using Python Flask. Then, we used Clowiz AppGenerator to generate the required code for a complete project. 

Thank you !

Python Flask Webdev Backend tutorial

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Flask Tutorial 11 - Deploy Python Flask App on Heroku

Hello! Welcome to the Python Flask Tutorial series. In this series, we'll learn about Flask, a micro framework built using Python, with the help of a project! In this video, We will deploy the flask application on the internet using Heroku. So we will see the process of Deploying a Flask Application to Heroku.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Modules Tutorial - Python Tutorial for Beginners

This Edureka session on Python Modules Tutorial will help you understand the concept of modules in python, why, and how we can use modules in Python.

Tutorial: Web Scraping with Python Using Beautiful Soup

Web scraping allows us to extract information from web pages. In this tutorial, you'll learn how to perform web scraping with Python and BeautifulSoup.The internet is an absolutely massive source of data. Unfortunately, the vast majority if it isn’t available in conveniently organized CSV files for download and analysis. If you want to capture data from many websites, you’ll need to try web scraping.