質問編集履歴
1
書いたコードを追記
title
CHANGED
File without changes
|
body
CHANGED
@@ -4,6 +4,276 @@
|
|
4
4
|
|
5
5
|
cloud9でのプレビューでは、問題ないのですが、Herokuにデプロイしたものが同様の動きをせず困っております。
|
6
6
|
|
7
|
+
特にログイン後の「edit.html」から「index.html」にリダイレクトするときや、「index.html」で再読み込みをするときに頻発しております。
|
8
|
+
|
9
|
+
```stokupile.py
|
10
|
+
#!/usr/bin/env python
|
11
|
+
# coding: utf-8
|
12
|
+
|
13
|
+
import sqlite3
|
14
|
+
from flask import Flask, render_template, request, redirect, url_for, session, flash
|
15
|
+
# from flask.ext.session import Session は廃止されている
|
16
|
+
from flask_session import Session
|
17
|
+
import os
|
18
|
+
|
19
|
+
|
20
|
+
app = Flask(__name__)
|
21
|
+
app.secret_key = os.urandom(24)
|
22
|
+
SESSION_TYPE = 'filesystem'
|
23
|
+
app.config.from_object(__name__)
|
24
|
+
sess = Session()
|
25
|
+
|
26
|
+
sqlite_path = 'db/stockpile.db'
|
27
|
+
users_db_path = 'db/users.db'
|
28
|
+
|
29
|
+
|
30
|
+
def get_db_connection():
|
31
|
+
connection = sqlite3.connect(sqlite_path)
|
32
|
+
connection.row_factory = sqlite3.Row
|
33
|
+
return connection
|
34
|
+
|
35
|
+
def get_user_db_connection():
|
36
|
+
connection = sqlite3.connect(users_db_path)
|
37
|
+
connection.row_factory = sqlite3.Row
|
38
|
+
return connection
|
39
|
+
|
40
|
+
|
41
|
+
@app.before_request
|
42
|
+
def before_request():
|
43
|
+
# # 静的ファイルへのアクセスについては、チェック対象としない
|
44
|
+
# if request.path.startswith('/static/'):
|
45
|
+
# return
|
46
|
+
# セッションにusernameが保存されている.つまりログイン済み
|
47
|
+
if session.get("username") == "admin":
|
48
|
+
return
|
49
|
+
# リクエストパスがログインページに関する場合
|
50
|
+
if request.path == '/login':
|
51
|
+
return
|
52
|
+
# ログインされておらず,インデックスに関するリクエストの場合
|
53
|
+
if request.path == '/':
|
54
|
+
return
|
55
|
+
# ログインされておらず,ログインページに関するリクエストでない場合
|
56
|
+
return render_template('index.html')
|
57
|
+
|
58
|
+
|
59
|
+
@app.route("/")
|
60
|
+
def index():
|
61
|
+
if session.get("username") == "admin":
|
62
|
+
connection = get_db_connection()
|
63
|
+
cursor = connection.cursor()
|
64
|
+
res = cursor.execute('SELECT * FROM stockpile')
|
65
|
+
return render_template('index.html', stock_list=res.fetchall(),
|
66
|
+
username=session["username"], password=session["password"])
|
67
|
+
else:
|
68
|
+
connection = get_db_connection()
|
69
|
+
cursor = connection.cursor()
|
70
|
+
res = cursor.execute('SELECT * FROM stockpile')
|
71
|
+
return render_template('index.html', stock_list=res.fetchall())
|
72
|
+
|
73
|
+
|
74
|
+
# 個人認証を行い,正規のアカウントか確認する
|
75
|
+
def _is_account_valid():
|
76
|
+
username = request.form.get('username')
|
77
|
+
password = request.form.get("password")
|
78
|
+
# この例では,ユーザ名にadminが指定されていれば正規のアカウントであるとみなしている
|
79
|
+
# ここで具体的な個人認証処理を行う.認証に成功であればTrueを返すようにする
|
80
|
+
if username == 'admin' and password == 'admin':
|
81
|
+
session["username"] = username
|
82
|
+
return True
|
83
|
+
return False
|
84
|
+
|
85
|
+
|
86
|
+
@app.route("/login", methods=["GET", "POST"])
|
87
|
+
def login():
|
88
|
+
if request.method == 'POST':
|
89
|
+
error = []
|
90
|
+
username = request.form.get("username", None)
|
91
|
+
password = request.form.get("password", None)
|
92
|
+
if username == "":
|
93
|
+
error.append("名前を入力して下さい")
|
94
|
+
if password == "":
|
95
|
+
error.append("パスワードを入力して下さい")
|
96
|
+
|
97
|
+
if error:
|
98
|
+
stockpile = request.form.to_dict()
|
99
|
+
return render_template("login.html", error_list=error)
|
100
|
+
|
101
|
+
if _is_account_valid():
|
102
|
+
session["username"] = username
|
103
|
+
session["password"] = password
|
104
|
+
flash('ログインしました', 'info')
|
105
|
+
return redirect(url_for('index'))
|
106
|
+
|
107
|
+
error.append("組み合わせが正しくありません")
|
108
|
+
return render_template("login.html", error_list=error)
|
109
|
+
|
110
|
+
|
111
|
+
elif request.method == 'GET':
|
112
|
+
return render_template("login.html")
|
113
|
+
|
114
|
+
else:
|
115
|
+
return render_template("index.html")
|
116
|
+
|
117
|
+
|
118
|
+
@app.route("/logout")
|
119
|
+
def logout():
|
120
|
+
session.pop("username", None)
|
121
|
+
return render_template("index.html")
|
122
|
+
|
123
|
+
|
124
|
+
@app.route("/add", methods=["GET", "POST"])
|
125
|
+
def add_stock():
|
126
|
+
if request.method == "GET":
|
127
|
+
"""移動先のテンプレートがformの中で辞書(stockpile)を使ってるから、
|
128
|
+
からのリストを定義しておかないとエラー発生
|
129
|
+
"""
|
130
|
+
stockpile = {}
|
131
|
+
return render_template("edit.html", type="add", stockpile=stockpile)
|
132
|
+
elif _is_account_valid():
|
133
|
+
connection = get_db_connection()
|
134
|
+
cursor = connection.cursor()
|
135
|
+
error = []
|
136
|
+
|
137
|
+
if not request.form["name"]:
|
138
|
+
error.append("商品名を入力して下さい")
|
139
|
+
if not request.form["stocknumber"]:
|
140
|
+
error.append("個数を入力して下さい")
|
141
|
+
if not request.form["duedate"]:
|
142
|
+
error.append("賞味期限を入力して下さい")
|
143
|
+
|
144
|
+
if error:
|
145
|
+
#name属性をkey,入力をvalueにした辞書を作成?
|
146
|
+
stockpile = request.form.to_dict()
|
147
|
+
return render_template("edit.html", type="add", stockpile=stockpile, error_list=error)
|
148
|
+
|
149
|
+
cursor.execute("INSERT INTO stockpile(name, stocknumber, duedate, memo) VALUES(?, ?, ?, ?)",
|
150
|
+
(request.form["name"],
|
151
|
+
request.form["stocknumber"],
|
152
|
+
request.form["duedate"],
|
153
|
+
request.form["memo"]))
|
154
|
+
connection.commit()
|
155
|
+
return redirect(url_for('index'))
|
156
|
+
|
157
|
+
|
158
|
+
@app.route("/delete/<int:id>")
|
159
|
+
def delete(id):
|
160
|
+
connection = get_db_connection()
|
161
|
+
cursor = connection.cursor()
|
162
|
+
cursor.execute("DELETE FROM stockpile WHERE id = ? ", (id,))
|
163
|
+
connection.commit()
|
164
|
+
return render_template("index.html")
|
165
|
+
|
166
|
+
|
167
|
+
@app.route("/edit/<int:id>")
|
168
|
+
def edit(id):
|
169
|
+
connection = get_db_connection()
|
170
|
+
cursor = connection.cursor()
|
171
|
+
res = cursor.execute("SELECT * FROM stockpile WHERE id = ? ", (id,))
|
172
|
+
return render_template("edit.html", type="edit", stockpile=res.fetchone())
|
173
|
+
|
174
|
+
|
175
|
+
@app.route("/update/<int:id>", methods=["POST"])
|
176
|
+
def update_stock(id):
|
177
|
+
error = []
|
178
|
+
|
179
|
+
if not request.form["name"]:
|
180
|
+
error.append("商品名を入力して下さい")
|
181
|
+
if not request.form["stocknumber"]:
|
182
|
+
error.append("個数を入力して下さい")
|
183
|
+
if not request.form["duedate"]:
|
184
|
+
error.append("期限を入力して下さい")
|
185
|
+
|
186
|
+
if error:
|
187
|
+
stockpile = request.form.to_dict()
|
188
|
+
return render_template("edit.html", type="edit", stockpile=stockpile, error_list=error)
|
189
|
+
|
190
|
+
connection = get_db_connection()
|
191
|
+
cursor = connection.cursor()
|
192
|
+
cursor.execute("UPDATE stockpile set name = ? , stocknumber = ? , duedate = ? , memo = ? where id = ?",
|
193
|
+
(request.form["name"],
|
194
|
+
request.form["stocknumber"],
|
195
|
+
request.form["duedate"],
|
196
|
+
request.form["memo"],
|
197
|
+
id))
|
198
|
+
connection.commit()
|
199
|
+
return redirect(url_for("index"))
|
200
|
+
|
201
|
+
|
202
|
+
if __name__ == '__main__':
|
203
|
+
# app.debug = True # デバッグモード有効化
|
204
|
+
# どこからでもアクセス可能に
|
205
|
+
app.run(host='0.0.0.0', port=8080, threaded=True)
|
7
206
|
```
|
8
207
|
|
208
|
+
```index.html
|
209
|
+
{% extends "layout.html" %}
|
210
|
+
{% block body %}
|
211
|
+
<body>
|
212
|
+
{% for message in get_flashed_messages() %}
|
213
|
+
<div class="alert alert-warning">
|
214
|
+
{{ message }}
|
215
|
+
</div>
|
216
|
+
{% endfor %}
|
217
|
+
<h1>在庫管理 アプリケーション</h1>
|
218
|
+
{% if session.username == "admin" %}
|
219
|
+
<table>
|
220
|
+
<tr>
|
221
|
+
<th>商品名</th>
|
222
|
+
<th>個数</th>
|
223
|
+
<th>賞味期限</th>
|
224
|
+
<th>メモ</th>
|
225
|
+
<th></th>
|
226
|
+
</tr>
|
227
|
+
{% for v in stock_list %}
|
228
|
+
<tr>
|
229
|
+
<td><a href="{{ url_for('edit', id=v['id'])}}">{{ v['name']}}</a></td>
|
230
|
+
<td>{{ v['stocknumber']}}</td>
|
231
|
+
<td>{{ v['duedate']}}</td>
|
232
|
+
<td>{{ v['memo']}}</td>
|
233
|
+
<td><a href={{ url_for("delete", id=v["id"]) }}>削除</a></td>
|
234
|
+
</tr>
|
235
|
+
{% endfor %}
|
236
|
+
</table>
|
237
|
+
<h3><a href="{{ url_for('add_stock')}}">在庫の追加</a></h3>
|
238
|
+
<h3><a href="{{ url_for('logout')}}">ログアウト</a></h3>
|
239
|
+
{% else %}
|
240
|
+
<h3><a href="{{ url_for('login')}}">ログイン</a></h3>
|
241
|
+
{% endif %}
|
242
|
+
</body>
|
243
|
+
{% endblock %}
|
9
|
-
```
|
244
|
+
```
|
245
|
+
|
246
|
+
```edit.html
|
247
|
+
{% extends "layout.html" %}
|
248
|
+
{% block body %}
|
249
|
+
<body>
|
250
|
+
|
251
|
+
<h1>在庫を編集する</h1>
|
252
|
+
|
253
|
+
<form method="post" action="{% if type == "add" %}{{ url_for('add_stock') }}{% else %}{{ url_for('update_stock', id=stockpile["id"]) }}{% endif %}">
|
254
|
+
{% if error_list %}
|
255
|
+
<ul>
|
256
|
+
{% for v in error_list %}
|
257
|
+
<li>{{ v }}</li>
|
258
|
+
{% endfor %}
|
259
|
+
</ul>
|
260
|
+
{% endif %}
|
261
|
+
<p>商品名<br/><input type="text" name="name" value="{{ stockpile['name'] }}"/></p>
|
262
|
+
<p>在庫数<br/><input type="int" name="stocknumber" value="{{ stockpile['stocknumber'] }}"/></p>
|
263
|
+
<p>期限<br/><input type="text" name="duedate" value="{{ stockpile['duedate'] }}"/></p>
|
264
|
+
<p>メモ<br/><input type="text" name="memo" value="{{ stockpile['memo'] }}" size="60"/></p>
|
265
|
+
{% if type == "add" %}
|
266
|
+
<button type="submit">在庫を追加</button>
|
267
|
+
{% else %}
|
268
|
+
<button type="submit">在庫を更新</button>
|
269
|
+
{% endif %}
|
270
|
+
</form>
|
271
|
+
<br/>
|
272
|
+
<a href="{{ url_for('index')}}">トップに戻る</a>
|
273
|
+
</body>
|
274
|
+
{% endblock %}
|
275
|
+
```
|
276
|
+
|
277
|
+
調べてみた限りではredisを利用してsessionをデータベースに保存するのがいいようなことはわかったのですが、Railsでのやり方や、英語のドキュメントしか見当たらず、理解することができませんでした。
|
278
|
+
|
279
|
+
ご教示いただけると幸いです。
|