How to connect Python & Flask with Yaml and CRUD operations
Did you miss reading our last Blog about “Understanding Python Flask and How to connect Python and Flask to a database. ”? If yes, please click here to go to our previous blog.
If not, it’s time to get started with our today’s new topic.
Today, we will be doing some cool stuff by integrating a Python Flask + YAML and performing the CRUD ( Create | Read | Update | Delete ) operations. But before we actually jump in, let’s have a glimpse of what is YAML?
Let’s explore Yaml.
Introduction of Yaml
YAML stands for “YAML Ain’t Markup Language”. Huh! The only thing in YAML that nobody can understand, is its Name. Better to call it, “Yet Another Markup Language”.
YAML is a data serialization language, which means a language that helps store complex data structures or data object states in a form that is easy to store, transfer, and most important is human readable.
In short, storing the data in a form that is more convenient to store and easily readable.
Let’s take an example of a class Employee and store its Object in YAML.
class Employee(object):
def init(self, name, id):
self.name = name
self.id = id
Let’s create an Object of Class Employee and try to convert it into YAML form and save its file name, employee.yaml
Employee1
name: John Desouza
id: 002
YAML supports storing the data in the form of List / Dictionary ( i.e. Key/Value Form). Let’s see how:
YAML List
The fruits stack into YAML, as you know fruits are taken in a cluster data structure as a list.
In YAML, all members of a list are lines beginning at the same indentation level starting with a "- "
(a dash and a space):
The following shows the output:
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
YAML Dictionary
A dictionary is represented in a simple key: value
form
(the colon must be followed by a space):
# A employee record
John :
name: John Desouza
job: Developer
skill: Python
We can also dictionaries and lists can also be represented in an abbreviated form if you want :
---
John: {name: John Desouza, job: Developer, skill: Python}
['Apple', 'Orange', 'Strawberry', 'Mango']
Now that we have a basic understanding of YAML concepts, we will be integrating our Python Flask App with YAML.
Setting up
Let’s create a separate folder, initialize our own virtual environment in it and install some requirements.
$ mkdir flaskblog
$ cd flaskblog$ python3 -m venv dev
$ source dev/bin/activate
(dev) $ _(dev) $ pip install flask
(dev) $ pip install pyyaml
Note: PyYAML is a YAML parser (a function or a piece of code that helps convert python-generated data into YAML.)
In your flaskblog
directory, open a file named data.yaml
for editing, use nano
, or your favorite text editor:
(dev) flaskblog $ touch data.yaml
(dev) flaskblog $ nano data.yamlTechnology:
- Devoops
- Cloud Computing
- Python developer
Now Let’s create a python file read.py. In this file, we will create a class and function.
(We have to write the code to read the YAML file inside the function.)
(dev) flaskblog $ touch read.py
(dev) flaskblog $ touch read.pyimport yaml
from yaml.loader import FullLoader
class Tech:
def data(self):
with open('data.yaml', 'r') as f:
data = yaml.load(f, Loader=FullLoader)
return(data)
Now moving further, we will create our main python file app.py.
In this file, import the Flask
object, and create a function that returns our action in the form of the HTTP response.
Step — 1
Let’s create a file :
(dev) flaskblog $ touch app.py
(dev) flaskblog $ nano app.pyfrom flask import Flask, render_template, request, redirect
from read import Tech
import yaml
from yaml import SafeLoader, FullLoader
app = Flask(__name__)
@app.route('/', methods =["GET", "POST"])
def home():
obj1 = navigation()
obj = obj1.data()
return render_template('index.jinja2', obj=obj)if __name__=='__main__':
app.run()
Let’s create a directory called template inside our flaskblog
directory, in that, create a file named index.jinja2
(dev) flaskblog $ mkdir templates
(dev) flaskblog $ cd templates
(dev) flaskblog/templates $ nano index.jinja2
Next, add the following HTML code inside index.jinja2. (It is a code for index.jinja2 file)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<<for>>, initial-scale=1.0">
<title>Document</title>
</head><body>
<div class="container">
<h2>Your Technology</h2>
<table class="table">
<thead>
<tr>
<th scope="col">Technology</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for x in obj.values() %}
{% for y in x %}
<tr>
<td scope="col">{{y}}</td> <td>
<form class="d-flex" action="#" method="post">
<!-- Button -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target=#>
edit
</button>
</form>
<form class="d-flex" action="#" method="post">
<input type="hidden" value={{y}} name="text">
<input type="submit" value = "Delete" class="btn btn-secondary" >
</form> </td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
<div class="content" style="text-align:center">
<form class="search" action="{{ url_for("edit")}}" method="post">
<button class="btn btn-outline-success" type="submit">Add Technology</button>
</form>
</div>
</body>
</html>
Now let’s run our application :
To run your web application, you’ll first tell Flask where to find the application (the app.py
file in your case) with the FLASK_APP
environment variable:
(dev) flaskblog $ export Flask_APP = app.py
Run the application using the flask run
command:
(dev) $ flask run
* Serving Flask app 'microblog.py' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Step — 2
Now let’s create our function add.
Again open our main python file i.e app.py, and add our second function.
(def add)
from flask import Flask, render_template, request, redirect
from read import Tech
import yaml
from yaml import SafeLoader, FullLoader
app = Flask(__name__)
@app.route('/', methods =["GET", "POST"])
def home():
obj1 = Tech()
obj = obj1.data()
if request.method == "POST":
refersh = request.form.get("refersh")
return render_template('index.jinja2', obj=obj)@app.route('/edit', methods =["GET", "POST"])
def edit():
obj1 = Tech()
obj = obj1.data()
return render_template('add.jinja2', obj=obj)
@app.route('/add', methods =["GET", "POST"])
def add():
obj1 = Tech()
obj = obj1.data()
if request.method == "POST":
add = request.form.get("add")
nav = [add]
with open('data.yaml', 'a') as f:
yaml.dump(nav, f)
return render_template("add.jinja2", obj=obj)if __name__=='__main__':
app.run()
Let’s create a second template file i.e add.jinja2 in the template folder.
(dev) flaskblog $ mkdir templates
(dev) flaskblog $ cd templates
(dev) flaskblog/templates $ nano add.jinja2
Next, add the following HTML code inside add.jinja2
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<<for>>, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<h2>Your Technology</h2>
<table class="table">
<thead>
<tr>
<th scope="col">Technology</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for x in obj.values() %}
{% for y in x %}
<tr>
<td scope="col">{{y}}</td>
<td>
<form class="d-flex" action="#" method="post">
<button class="btn btn-outline-success" type="submit">edit</button>
</form>
</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
<div class="content" style="text-align:center">
<form class="search" action="{{ url_for("add")}}" method="post">
<input class="form" name="add" placeholder="add" aria-label="add">
<button class="btn btn-outline-success" type="submit">Add </button>
</form>
<form class="search" action="{{ url_for("home")}}" method="post" >
<button class="btn btn-outline-success" type="submit">Refresh </button>
</form>
</div></body>
</html>
Now when we click on the Add Technology button:
We can see this page, we can add other technology and refresh it.
and we can see technology is added.
In the upcoming blog, we will be discussing other operations Updates and Delete.