[PYTHON] Try creating a CRUD function

# Introduction We use Flask to create an application from scratch and organize it so that you can learn the necessary technology.

-Creating a simple app with flask -Try to create a Home screen -Try to create an authentication function -Try to handle the database --Try to create CRUD function ← ★ Currently here

What is CRUD

CRUD is an acronym for Create, Read, Update, and Delete. In the blog application created this time, it is as follows.

--Create: New blog creation function (new data creation) --Read: Blog list display function and detailed display function (reading data) --Update: Blog update function (data update) --Delete: Blog deletion function (data deletion)

You can create a set of functions by satisfying CRUD. This function can also be applied when creating other applications.

Create

Blog posting screen creation

--Addition of navigation bar

<div class="collapse navbar-collapse" id="navbarNav">
  <ul class="nav navbar-nav navbar-lighy">
    {% if not session.logged_in %}
    <li class="nav-item">
      <a class="nav-link" href="{{ url_for('login') }}">LogIn</a>
    </li>
    {% else %}
    <li class="nav-item">
 <a class="nav-link" href="{{url_for('new_add')}}"> New registration </a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{{ url_for('logout') }}">Logout</a>
    </li>
    {% endif %}
  </ul>
</div>

--Posting form

{% extends "./layout.html" %}

{% block body %}
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
    <div class=form-group>
 <label for = "InputTitle"> Title </label>
        <input type="text" class="form-control" id="InputTitle" name=title>
    </div>

    <div class="form-group">
 <label for = "InputText"> Body </label>
        <textarea name=text id="InputText" rows="10" class="form-control"></textarea>
    </div>
 <button type = "submit" class = "btn btn-primary"> Create </button>
</form>
{% endblock %}
~~~
#### Creating a blog posting function

~~~:src/views.py
from src import app, db
from flask import flash
from flask import redirect
from flask import request
from flask import render_template
from flask import url_for
from flask import session

from src.domains.entry import Entry

User = {
    'username': 'test',
    'password': 'testpass'
}

@app.route('/')
def index():
    if not session.get('logged_in'):
        return redirect('/login')
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['username'] != User['username']:
 flash (f'username is different')
        elif request.form['password'] != User['password']:
 flash (f'password is different')
        else:
            session['logged_in'] = True
 flash ('logged in')
            return redirect('/')
    return render_template('login.html')

@app.route('/logout', methods=['GET'])
def logout():
    session.pop('logged_in', None)
 flash ('logged out')
    return redirect('/')

@app.route('/new_add', methods=['GET','POST'])
def new_add():
    return render_template('/new.html')

@app.route('/add_entry', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    entry = Entry(
        title = request.form['title'],
        text = request.form['text'])
    
    db.session.add(entry)
    db.session.commit()
 flash ('new article created')
    return redirect(url_for('index'))
~~~

 Read
#### List function

~~~:src/templates/index.html
{% extends "./layout.html" %}

{% block body %}
{% for entry in entries %}
<ul class="card">
    <div class="card-body">
        <h5 class="card-title">
            <a href="{{ url_for('show_entry', id=entry.id) }}">{{ entry.title }}</a>
        </h5>
    </div>
</ul>
{% else %}
 No posts
{% endfor %}

{% endblock %}
~~~

~~~:src/views.py
@app.route('/')
def index():
    if not session.get('logged_in'):
        return redirect('/login')
    entries = Entry.query.order_by(Entry.id.desc()).all()
    return render_template('index.html', entries=entries)
~~~

 ![スクリーンショット 2021-01-01 15.50.57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/618885/0adac676-a459-cb4b-55f9-08d788095ec8.png)

#### Detailed function

~~~:src/views.py
@app.route('/entry/<int:id>', methods=['GET'])
def show_entry(id):
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    entry = Entry.query.get(id)
    return render_template('show.html', entry=entry)
~~~

~~~:src/templates/show.html
{% extends "./layout.html" %}

{% block body %}
<h2>{{ entry.title }}</h2>
<br />

{{ entry.text }}

<br /><br />
 Post date: {{entry.create_at}}
{% endblock %}
~~~

 ![スクリーンショット 2021-01-01 15.49.51.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/618885/1d553c80-c5d8-482e-ea96-16968b8c87c9.png)


 Update
 --Create edit button

~~~:src/templates/show.html
{% extends "./layout.html" %}

{% block body %}
<h2>{{ entry.title }}</h2>
<br />
{{ entry.text }}
<br /><br />
 Post date: {{entry.create_at}}
<br /><br />
<div class="btn-group">
    <form action="{{ url_for('edit_entry', id=entry.id) }}" method="GET">
        <button type="submit" class="btn btn-secondary">Edit</button>
    </form>
</div>

{% endblock %}
~~~

 --Creating an edit screen

~~~:src/templates/edit.html
{% extends "./layout.html" %}

{% block body %}
<form action="{{ url_for('update_entry', id=entry.id) }}" method="POST" class="add-entry">
    <div class="form-group">
 <label> Title </label>
        <input type="text" class="form-control" name="title" value={{ entry.title}}>
    </div>
    <div class="form-group">
 <label> Body </label>
        <textarea class="form-control" name="text" cols="100" rows="3">{{ entry.text | safe }}</textarea>
    </div>
    <button type="submit" class="btn btn-primary">Update</button>
</form>
{% endblock %}
~~~

 --Creating an update function

~~~:src.views.py
@app.route('/entry/<int:id>/edit', methods=['GET'])
def edit_entry(id):
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    entry = Entry.query.get(id)
    return render_template('edit.html', entry=entry)

@app.route('/entry/<int:id>/update', methods=['POST'])
def update_entry(id):
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    entry = Entry.query.get(id)
    entry.title = request.form['title']
    entry.text = request.form['text']
    db.session.merge(entry)
    db.session.commit()
 flash ('article updated')
    return redirect(url_for('index'))
~~~

 --Detail screen
 ![スクリーンショット 2021-01-01 16.22.59.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/618885/ad1557d3-b9c1-e7b1-5c21-8375ef709c6d.png)

 - Editing screen
 ![スクリーンショット 2021-01-01 16.23.21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/618885/02819324-22de-d5fe-46b9-5724323e20a3.png)


 Delete
 --Create a delete button

~~~:src/templates/show.html
{% extends "./layout.html" %}

{% block body %}
<h2>{{ entry.title }}</h2>
<br />

{{ entry.text }}

<br /><br />
 Post date: {{entry.create_at}}
<br /><br />
<div class="btn-group">
    <form action="{{ url_for('edit_entry', id=entry.id) }}" method="GET">
        <button type="submit" class="btn btn-secondary">Edit</button>
    </form>

    <form action="{{ url_for('delete_entry', id=entry.id) }}" method="POST">
        <button type="submit" class="btn btn-danger" style="margin-left:5px">Delete</button>
    </form>
</div>

{% endblock %}
~~~

 --Creating a delete function

~~~:src/views.py
@app.route('/entry/<int:id>/delete', methods=['POST'])
def delete_entry(id):
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    entry = Entry.query.get(id)
    db.session.delete(entry)
    db.session.commit()
 flash ('post deleted')
    return redirect(url_for('index'))
~~~ 

 --Detail screen
 ![スクリーンショット 2021-01-01 16.34.24.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/618885/9fc8a471-78a0-8be0-7699-103a28862e33.png)

 --Screen after deletion
 ![スクリーンショット 2021-01-01 16.33.59.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/618885/6dfb53ba-1903-cc44-eb14-65d6b801610a.png)



Recommended Posts

Try creating a CRUD function
[Piyopiyokai # 1] Let's play with Lambda: Creating a Lambda function
Try creating a FizzBuzz problem with a shell program
[Day 9] Creating a model
Creating a Home screen
4. Creating a structured program
Creating an authentication function
Differentiate a two-variable function
Make a function decorator
Creating a scraping tool
Creating a dataset loader
Try creating a compressed file using Python and zlib
Try function optimization with Optuna
Try creating a Deep Zoom file format .DZI in Python
Create a function in Python
Try function optimization using Hyperopt
Write a kernel density function
Try programming with a shell!
How to call a function
Let's try a shell script
Try adding a simple image baking function as an add-on
Let's draw a logistic function
Try creating a Kubernetes pod from a GitLab Container Registry image
(For beginners) Try creating a simple web API with Django
Try running a function written in Python using Fn Project
Try to select a language
What is a callback function?
Block device RAM Disk Creating a device
[Python] What is a zip function?
Call a Python function from p5.js.
Creating a web application using Flask ②
Creating a wav file split program
Try to draw a Bezier curve
Try throwing a query in Redash
Step by Step for creating a Dockerfile
Creating a decision tree with scikit-learn
Creating a Flask server with Docker
A function that returns a random name
Creating a voice transcription web application
Creating a simple table using prettytable
How to make a recursive function
Creating a simple app with flask
[Python] Make the function a lambda function
Python-dynamically call a function from a string
Creating a web application using Flask ①
[Python] Creating a scraping tool Memo
Precautions when creating a Python generator
Creating a learning model using MNIST
Creating a web application using Flask ③
Create a CRUD API using FastAPI
When creating a matrix in a list
Creating a web application using Flask ④
[Python] Chapter 03-01 turtle graphics (creating a turtle)