Flask-Create a Todo list with CSRF measures in Flask with WTF

It is a memorandum. It is a solid writing. How to use Flask-WTF doesn't work unless you put it in the input with hidden in the template ...

code

todo.py


import os
import sqlite3
import datetime
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, session
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
csrf = CSRFProtect(app)


@app.route('/')
def show_entries():
    con = sqlite3.connect('todo.db')
    c = con.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS message(data_id,msg,date_time)''')
    result = con.execute('''select * from message order by data_id desc''')

    return render_template('index.html', result=result)


@app.route('/add', methods=['GET', 'POST'])
def send():
    if request.method == 'POST':
        msg = request.form['msg']
        if not msg:
            con = sqlite3.connect('todo.db')
            c = con.cursor()
            alert = 'Please enter'
            return render_template('index.html', alert=alert)
        else:
            date_time = datetime.datetime.today()
            data_id = date_time.strftime("%Y%m%d%H%M%S")
            con = sqlite3.connect('todo.db')
            c = con.cursor()
            c.execute('INSERT INTO message VALUES (?,?,?)',(data_id,msg,date_time))
            con.commit()
            result = con.execute('''select * from message order by data_id desc''')

    return render_template('index.html', result=result)

@app.route('/delete_data', methods=['GET', 'POST'])
def delete_data():
    if request.method == 'POST':
        data_ids= request.form['action']
        con = sqlite3.connect('todo.db')
        c = con.cursor()
        query = "DELETE FROM message WHERE data_id=?"
        c.execute(query,(data_ids,))
        con.commit()
        result = con.execute('''select * from message order by data_id desc''')
    return render_template('index.html', result=result)


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

index.html


{% extends "base.html" %}
{% block content %}
<form action="{{ url_for('send') }}" method="post">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
  <input type="text" name="msg" value="">
  <input type="submit" value="Send">
</form>

{% if alert %}
<p>{{ alert}}</p>
{% endif %}

<form action="{{ url_for('delete_data') }}" method="post" enctype="multipart/form-data">
  <ul>
    {% for entry in result %}
      <li>
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
        <input type="checkbox" name="action" value="{{ entry[0] }}">{{ entry[1] }}:{{ entry[2] }}
      </li>
    {% endfor %}
  </ul>
  <input type="submit" value="Delete">
</form>
{% endblock %}

base.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/css/style.css">
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <title>File</title>
</head>
<body>
  <div class="container">
    <div class="row">
        {% block content %}
        {% endblock %}
    </div>
  </div>
</body>
</html>

Recommended Posts

Flask-Create a Todo list with CSRF measures in Flask with WTF
A simple to-do list created with Python + Django
I want to transition with a button in flask
Create a Todo app with Django ③ Create a task list page
Create a list in Python with all followers on twitter
Created a reading record book in conjunction with PostgreSQL in Flask
Behavior when giving a list with shell = True in subprocess
Get a list of files in a folder with python without a path
[python] Manage functions in a list
Create a CSV reader in Flask
Creating a Flask server with Docker
Creating a simple app with flask
When creating a matrix in a list
Get a list of packages installed in your current environment with python
Generate a list packed with the number of days in the current month.
Receive a list of the results of parallel processing in Python with starmap
I got stuck in a flask application redirect with a reverse proxy in between
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Display a list of alphabets in Python 3
Draw a heart in Ruby with PyCall
Make a rare gacha simulator with Flask
Page cache in Python + Flask with Flask-Caching
Change the list in a for statement
Create a web service with Docker + Flask
How to get a list of files in the same directory with python