Flask is a Python micro web framework. Flask is “micro” because it omits native tools and libraries for an “only installs what you need” approach.
In this shot, we will create a to-do app where you can add to-dos (activities) and even mark when you are done with any of the activities. This will give you a grasp of the popular web framework Flask.
First, run the following commands to install the required dependencies:
pip install pipenvpipenv shellpipenv install Flaskpipenv install Flask-SQLAlchemypipenv install SQLAlchemy
SQLalchemy is an Object Relational Mapper(ORM).
Create a file and name it
from flask import Flask, request, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from sqlalchemy import desc
#first step in starting a flask app
app = Flask(__name__)
#configuring the database
app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
#initializing sqlalchemy
db=SQLAlchemy(app)
#creating of the model
class Note(db.Model):
id= db.Column(db.Integer(), primary_key=True)
text = db.Column(db.String(100))
complete =db.Column(db.Boolean())
date = db.Column(db.DateTime(timezone=True), default=func.now())
#home route
@app.route('/')
def home():
# making the data to render from a descending order according to the datetime
incomplete =Note.query.filter_by(complete=False).order_by(desc(Note.date)).all()
complete = Note.query.filter_by(complete=True).order_by(desc(Note.date)).all()
return render_template('home.html', incomplete =incomplete, complete=complete)
#route for adding todos
@app.route('/add', methods=['POST'])
def add():
note = Note(text=request.form['todoitem'], complete=False)
db.session.add(note)
db.session.commit()
return redirect (url_for('home'))
#route to mark completed task
@app.route('/complete/<id>')
def complete(id):
note = Note.query.filter_by(id=int(id)).first()
note.complete = True
db.session.commit()
return redirect (url_for('home'))
#initiating the flask framework
if __name__ == "__main__":
app.run(debug=True)
Create a folder and name it “templates.” Inside the “templates” folder, create a file and name it
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet"integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"></head><body><div class="container"><h2>Todo List</h2><div>add a new todo list</div><form action="{{ url_for('add') }}" method="POST" ><input class="form-control" type="text" name="todoitem"><input value="Add item" type="submit" ></form><div class="form-group"><h3>incomplete items</h3><ul>{% for todo in todos %}<li style="font-size: 30pt">{{ todo.text }} <a href="{{ url_for('complete', id=todo.id) }}">mark as complete</a> </li>{% endfor %}</ul><h3>incomplete items</h3><ul>{% for todo in incomplete %}<li style="font-size: 30pt">{{ todo.text }} <a href="{{ url_for('complete', id=todo.id) }}">mark as complete</a> </li>{% endfor %}</ul><h3>complete</h3><ul>{% for todo in complete %}<li style="font-size: 30pt">{{ todo.text }}</li>{% endfor %}</ul></div></div><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js"integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script></body></html>
In your terminal, run this code to create a database:
pythonfrom app import dbdb.create_all()exit()
Then run:
python app.py
Your app should be up and running locally at http://127.0.0.1:5000/
.
You should be able to see something like this:
Flask is used to efficiently build small apps and can save time. It uses an ORM(SQLAlchemy), which helps to easily map out a database. The to-do app shows us how to use Flask to build a to-do app and also make use of ORM to map out the model.