How to build a CRUD application using Flask (Python Framework)

John
Python, Flask, Django Tutorials and Tips
4 min readMar 22, 2016

Share this tutorial w/ your followers on Twitter. Click this link to tweet this tutorial: https://goo.gl/MtIA1L

The application that we will build is a very simple database driven note taking application. This tutorial is for beginners who want to learn how to use Flask for developing websites or web applications.

This tutorial assumes that you already installed Python and SQlite. If Python and SQlite is not yet installed in your computer, install them first. If the Python version that you installed is 2.5 and up, then you don’t need to install SQlite since Python 2.5 and up already comes with SQlite.

Python: https://www.python.org/

SQlite: https://www.sqlite.org/download.html

Things that we will cover in this tutorial:

  • Using templates
  • Saving a record in the database
  • Fetching a record in the database
  • Updating a record in the database
  • Deleting a record in the database

App requirements:

  • The user should be able to create a note (a note can have a title and a body)
  • The user should be able to view a list of notes
  • The user should be able to edit a note
  • The user should be able to delete a note

Okay, let’s start.

We first need to install Flask and Flask-SQLAlchemy.

Open a terminal window (command line in Windows) and run these commands one after another:

pip install Flaskpip install Flask-SQLAlchemy

Now create a folder where you will put the source code of the application. Let’s use note_app as the name of the folder.

Inside the folder that you created, create a file and name it main.py

We will be using templates in this tutorial so let’s also create a folder where we will put the templates. Use templates as the name of the folder. The templates folder should be inside the note_app folder. When using templates, Flask will automatically look for the template in the templates folder, that’s why we are using templates as the name of the folder.

Reference: http://flask.pocoo.org/docs/0.10/quickstart/#rendering-templates

Now let’s start writing code.

In main.py:

from flask import Flask, render_template, redirect, request
from flask_sqlalchemy import SQLAlchemy
import os

Next, we create our actual application and create the SQLAlchemy object by passing it the application.

app = Flask(__name__)basedir = os.path.abspath(os.path.dirname(__file__))
app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///’ + os.path.join(basedir, ‘app.sqlite’)
db = SQLAlchemy(app)

Gain the skills you need to be a pro at Python development. Visit: http://treehouse.7eer.net/c/245500/245646/3944

Next, we will create a model:

class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
body = db.Column(db.Text)
def __init__(self, title, body):
self.title = title
self.body = body

The Note model above will be used for creating, fetching, updating and deleting a note in the database. Our Note model has an id attribute which is an integer and will serve as the primary key, a title which is a string which can contain a maximum of 80 characters (you can change the maximum number of characters if you want, we’re just setting it to 80 in this tutorial), and a body which is a text.

Integer, String and Text are data types, you can view a list of available data types that you can use in the documentation of SQLAlchemy: http://docs.sqlalchemy.org/en/latest/core/type_basics.html#generic-types

Go to your terminal window and run the following commands one after another:

python
from main import db
db.create_all()

The commands above will initialize the database. It will create the database and a table named note.

Now we will create a function and we will use the route() decorator to bind the function to a URL.

@app.route(“/”)
def home():
return render_template(“home.html”)

Basically, what will happen is when the user visits the home page (example: http://mywebsite.com) of our website, flask will use the home() function that we defined above. Inside the home() function, we are rendering a template called home.html

Reference: http://flask.pocoo.org/docs/0.10/quickstart/#routing

Now open home.html and paste the contents below:

<h3>Note Taking App</h3>
<a href=”/notes”>View all notes</a>
<br>
<a href=”/notes/create”>Create a note</a>

Go back to main.py and paste the code below in the bottom of the file:

if __name__ == “__main__”:
app.run(debug=True)

The contents of your main.py file should now look similar to this:

from flask import Flask, render_template, redirect, request
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)basedir = os.path.abspath(os.path.dirname(__file__))
app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///’ + os.path.join(basedir, ‘app.sqlite’)
db = SQLAlchemy(app)
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
body = db.Column(db.Text)
def __init__(self, title, body):
self.title = title
self.body = body
@app.route(“/”)
def home():
return render_template(“home.html”)
if __name__ == “__main__”:
app.run(debug=True)

Now let’s run the application by running this command in your terminal window (make sure you are inside the note_app folder when running the command below):

python main.py

Now visit http://127.0.0.1:5000/ in your browser.

You should now see the home page.

Our current app is not yet fully functional. In part 2, we will start adding the create a note page, note list page etc…

Update: Part 2 is now published: https://medium.com/python-flask-django-tutorials-and-tips/how-to-build-a-crud-application-using-flask-python-framework-part-2-6859b4730350

Want to get updated when I publish another tutorial? Follow me on Twitter: https://twitter.com/John200Ok

--

--