こちらでは,flaskでtodoアプリを作成する例について解説していきます.
flaskのインストール
デフォルトが3系になっている場合はpipでいいですが
pip3で基本インストールです。
sh
pip3 install flask
または
pip install flask
プロジェクト構成
flask_todo_app/
│── app.py (Flaskアプリのメインファイル)
│── templates/
│ ├── index.html (タスク一覧のページ)
│ ├── add.html (タスク追加ページ)
└── static/
└── style.css (CSSファイル)
app.py
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# シンプルなToDoリスト(メモリ上で管理)
tasks = []
@app.route('/')
def index():
return render_template('index.html', tasks=tasks)
@app.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
task = request.form.get('task')
if task:
tasks.append(task)
return redirect(url_for('index'))
return render_template('add.html')
@app.route('/delete/<int:task_id>')
def delete(task_id):
if 0 <= task_id < len(tasks):
tasks.pop(task_id)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
templates/index.html(タスク一覧ページ)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ToDoリスト</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>ToDoリスト</h1>
<ul>
{% for task in tasks %}
<li>{{ task }} <a href="{{ url_for('delete', task_id=loop.index0) }}">削除</a></li>
{% endfor %}
</ul>
<a href="{{ url_for('add') }}">タスクを追加</a>
</body>
</html>
templates/add.html(タスク追加ページ)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>タスク追加</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>タスク追加</h1>
<form method="post">
<input type="text" name="task" required>
<button type="submit">追加</button>
</form>
<a href="{{ url_for('index') }}">戻る</a>
</body>
</html>
static/style.css(CSSの簡単なスタイル)
body {
font-family: Arial, sans-serif;
text-align: center;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 5px 0;
}
稼働
下記のコマンドで起動です
python app.py
下記URLでアプリが見れます
http://127.0.0.1:5000/
かなり単純に作成したものでgithubにも流しているので
こちらはcookiecutterを使用してるのでREADME.mdをみて
稼働お願い致します。cookiecutterについては下記の記事より