7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flask-WTFでCSRF対策をしたTodoリストをFlaskで作る

Last updated at Posted at 2017-06-01

備忘録です。べた書きです。
Flask-WTFの使い方はテンプレート内にhiddenでインプットに入れとかないと動かないんですね・・・。

#コード

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 = '入力してください'
            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="送信">
</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="削除">
</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>
7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?