DEV Community

CBAD
CBAD

Posted on

Creating a Simple CRUD App with Flask.

Motivation
Hello, fellow developers. This week I am going to create a simple CRUD app using Flask. My goal is to give anyone looking to learn Flask a quick bite on how it works. I'll start by showing what we are going to build, then I'll list the necessary dependencies, and finally, I'll show the steps to create our application. Cheers!
What We're Building

Install Dependencies
If you're developing on Mac or Linux you should already have python installed. If you're on windows you can download python from, https://www.python.org/downloads/.
Check your python installation by running the following command in your terminal:
python --version

Python 3.8.2
Next in our project directory, we want to install "Flask" and "flask_sqlalchemy". Today I'll be using python3 so I'll use "pip3" for installation.
pip3 install flask flask-sqlalchemy
Hello World
With our dependencies out of the way, let's create a simple route to test our installations. I'll start by creating a file named "app.py" and adding the following code inside.
Then in our terminal, we can run our file and if all is correct we will see our hello message in our browser!
python3 app.py
Rendering HTML
Now let's make our route serve an HTML page. First, in our same project directory, we'll create a folder called "templates". Inside this folder, we will create a file called "index.html" and fill it with the following boilerplate code.
Now back in our "app.py" file. We will add an import from flask called "render_template". Also, where we previously were returning a string in our routing function we will instead return "render_template('index.html')".
Now if we refresh our browser we should see our HTML being rendered!
Initializing our Database & Creating our Model
In our app.py file we'll add the following imports and configurations:
On line 2 we import "flask_sqlalchemy, on line 3 we import "datetime "for later use in our model, and on lines 6 and 7 we initialize our database. Now we can go ahead and create our Dog class.
Our dog model has little attributes just for demonstration purposes. We have an Id that will serve as the primary key, a name, and a birthday that is recorded on creation. Finally, our repr method returns a string representation of every created dog by interpolating its "id" property.
Now in our terminal, we will run "python3" in order to enter a python environment.
python3

Next, we run:
from app import db
db.create_all()
exit()
If all goes correctly we should see a "test.db" created in our project directory.

Top comments (1)

Collapse
 
dabjazz profile image
Yash_Jaiswal

Thank you sir for creating this post. I'm a student who is studying native android development and have no idea about web development and backend services. I need this knowledge for my mini project.