質問編集履歴

1

書いたコードを追記

2018/05/22 12:17

投稿

nokonoko_1203
nokonoko_1203

スコア17

test CHANGED
File without changes
test CHANGED
@@ -10,8 +10,548 @@
10
10
 
11
11
 
12
12
 
13
+ 特にログイン後の「edit.html」から「index.html」にリダイレクトするときや、「index.html」で再読み込みをするときに頻発しております。
14
+
15
+
16
+
17
+ ```stokupile.py
18
+
19
+ #!/usr/bin/env python
20
+
21
+ # coding: utf-8
22
+
23
+
24
+
25
+ import sqlite3
26
+
27
+ from flask import Flask, render_template, request, redirect, url_for, session, flash
28
+
29
+ # from flask.ext.session import Session は廃止されている
30
+
31
+ from flask_session import Session
32
+
33
+ import os
34
+
35
+
36
+
37
+
38
+
39
+ app = Flask(__name__)
40
+
41
+ app.secret_key = os.urandom(24)
42
+
43
+ SESSION_TYPE = 'filesystem'
44
+
45
+ app.config.from_object(__name__)
46
+
47
+ sess = Session()
48
+
49
+
50
+
51
+ sqlite_path = 'db/stockpile.db'
52
+
53
+ users_db_path = 'db/users.db'
54
+
55
+
56
+
57
+
58
+
59
+ def get_db_connection():
60
+
61
+ connection = sqlite3.connect(sqlite_path)
62
+
63
+ connection.row_factory = sqlite3.Row
64
+
65
+ return connection
66
+
67
+
68
+
69
+ def get_user_db_connection():
70
+
71
+ connection = sqlite3.connect(users_db_path)
72
+
73
+ connection.row_factory = sqlite3.Row
74
+
75
+ return connection
76
+
77
+
78
+
79
+
80
+
81
+ @app.before_request
82
+
83
+ def before_request():
84
+
85
+ # # 静的ファイルへのアクセスについては、チェック対象としない
86
+
87
+ # if request.path.startswith('/static/'):
88
+
89
+ # return
90
+
91
+ # セッションにusernameが保存されている.つまりログイン済み
92
+
93
+ if session.get("username") == "admin":
94
+
95
+ return
96
+
97
+ # リクエストパスがログインページに関する場合
98
+
99
+ if request.path == '/login':
100
+
101
+ return
102
+
103
+ # ログインされておらず,インデックスに関するリクエストの場合
104
+
105
+ if request.path == '/':
106
+
107
+ return
108
+
109
+ # ログインされておらず,ログインページに関するリクエストでない場合
110
+
111
+ return render_template('index.html')
112
+
113
+
114
+
115
+
116
+
117
+ @app.route("/")
118
+
119
+ def index():
120
+
121
+ if session.get("username") == "admin":
122
+
123
+ connection = get_db_connection()
124
+
125
+ cursor = connection.cursor()
126
+
127
+ res = cursor.execute('SELECT * FROM stockpile')
128
+
129
+ return render_template('index.html', stock_list=res.fetchall(),
130
+
131
+ username=session["username"], password=session["password"])
132
+
133
+ else:
134
+
135
+ connection = get_db_connection()
136
+
137
+ cursor = connection.cursor()
138
+
139
+ res = cursor.execute('SELECT * FROM stockpile')
140
+
141
+ return render_template('index.html', stock_list=res.fetchall())
142
+
143
+
144
+
145
+
146
+
147
+ # 個人認証を行い,正規のアカウントか確認する
148
+
149
+ def _is_account_valid():
150
+
151
+ username = request.form.get('username')
152
+
153
+ password = request.form.get("password")
154
+
155
+ # この例では,ユーザ名にadminが指定されていれば正規のアカウントであるとみなしている
156
+
157
+ # ここで具体的な個人認証処理を行う.認証に成功であればTrueを返すようにする
158
+
159
+ if username == 'admin' and password == 'admin':
160
+
161
+ session["username"] = username
162
+
163
+ return True
164
+
165
+ return False
166
+
167
+
168
+
169
+
170
+
171
+ @app.route("/login", methods=["GET", "POST"])
172
+
173
+ def login():
174
+
175
+ if request.method == 'POST':
176
+
177
+ error = []
178
+
179
+ username = request.form.get("username", None)
180
+
181
+ password = request.form.get("password", None)
182
+
183
+ if username == "":
184
+
185
+ error.append("名前を入力して下さい")
186
+
187
+ if password == "":
188
+
189
+ error.append("パスワードを入力して下さい")
190
+
191
+
192
+
193
+ if error:
194
+
195
+ stockpile = request.form.to_dict()
196
+
197
+ return render_template("login.html", error_list=error)
198
+
199
+
200
+
201
+ if _is_account_valid():
202
+
203
+ session["username"] = username
204
+
205
+ session["password"] = password
206
+
207
+ flash('ログインしました', 'info')
208
+
209
+ return redirect(url_for('index'))
210
+
211
+
212
+
213
+ error.append("組み合わせが正しくありません")
214
+
215
+ return render_template("login.html", error_list=error)
216
+
217
+
218
+
219
+
220
+
221
+ elif request.method == 'GET':
222
+
223
+ return render_template("login.html")
224
+
225
+
226
+
227
+ else:
228
+
229
+ return render_template("index.html")
230
+
231
+
232
+
233
+
234
+
235
+ @app.route("/logout")
236
+
237
+ def logout():
238
+
239
+ session.pop("username", None)
240
+
241
+ return render_template("index.html")
242
+
243
+
244
+
245
+
246
+
247
+ @app.route("/add", methods=["GET", "POST"])
248
+
249
+ def add_stock():
250
+
251
+ if request.method == "GET":
252
+
253
+ """移動先のテンプレートがformの中で辞書(stockpile)を使ってるから、
254
+
255
+ からのリストを定義しておかないとエラー発生
256
+
257
+ """
258
+
259
+ stockpile = {}
260
+
261
+ return render_template("edit.html", type="add", stockpile=stockpile)
262
+
263
+ elif _is_account_valid():
264
+
265
+ connection = get_db_connection()
266
+
267
+ cursor = connection.cursor()
268
+
269
+ error = []
270
+
271
+
272
+
273
+ if not request.form["name"]:
274
+
275
+ error.append("商品名を入力して下さい")
276
+
277
+ if not request.form["stocknumber"]:
278
+
279
+ error.append("個数を入力して下さい")
280
+
281
+ if not request.form["duedate"]:
282
+
283
+ error.append("賞味期限を入力して下さい")
284
+
285
+
286
+
287
+ if error:
288
+
289
+ #name属性をkey,入力をvalueにした辞書を作成?
290
+
291
+ stockpile = request.form.to_dict()
292
+
293
+ return render_template("edit.html", type="add", stockpile=stockpile, error_list=error)
294
+
295
+
296
+
297
+ cursor.execute("INSERT INTO stockpile(name, stocknumber, duedate, memo) VALUES(?, ?, ?, ?)",
298
+
299
+ (request.form["name"],
300
+
301
+ request.form["stocknumber"],
302
+
303
+ request.form["duedate"],
304
+
305
+ request.form["memo"]))
306
+
307
+ connection.commit()
308
+
309
+ return redirect(url_for('index'))
310
+
311
+
312
+
313
+
314
+
315
+ @app.route("/delete/<int:id>")
316
+
317
+ def delete(id):
318
+
319
+ connection = get_db_connection()
320
+
321
+ cursor = connection.cursor()
322
+
323
+ cursor.execute("DELETE FROM stockpile WHERE id = ? ", (id,))
324
+
325
+ connection.commit()
326
+
327
+ return render_template("index.html")
328
+
329
+
330
+
331
+
332
+
333
+ @app.route("/edit/<int:id>")
334
+
335
+ def edit(id):
336
+
337
+ connection = get_db_connection()
338
+
339
+ cursor = connection.cursor()
340
+
341
+ res = cursor.execute("SELECT * FROM stockpile WHERE id = ? ", (id,))
342
+
343
+ return render_template("edit.html", type="edit", stockpile=res.fetchone())
344
+
345
+
346
+
347
+
348
+
349
+ @app.route("/update/<int:id>", methods=["POST"])
350
+
351
+ def update_stock(id):
352
+
353
+ error = []
354
+
355
+
356
+
357
+ if not request.form["name"]:
358
+
359
+ error.append("商品名を入力して下さい")
360
+
361
+ if not request.form["stocknumber"]:
362
+
363
+ error.append("個数を入力して下さい")
364
+
365
+ if not request.form["duedate"]:
366
+
367
+ error.append("期限を入力して下さい")
368
+
369
+
370
+
371
+ if error:
372
+
373
+ stockpile = request.form.to_dict()
374
+
375
+ return render_template("edit.html", type="edit", stockpile=stockpile, error_list=error)
376
+
377
+
378
+
379
+ connection = get_db_connection()
380
+
381
+ cursor = connection.cursor()
382
+
383
+ cursor.execute("UPDATE stockpile set name = ? , stocknumber = ? , duedate = ? , memo = ? where id = ?",
384
+
385
+ (request.form["name"],
386
+
387
+ request.form["stocknumber"],
388
+
389
+ request.form["duedate"],
390
+
391
+ request.form["memo"],
392
+
393
+ id))
394
+
395
+ connection.commit()
396
+
397
+ return redirect(url_for("index"))
398
+
399
+
400
+
401
+
402
+
403
+ if __name__ == '__main__':
404
+
405
+ # app.debug = True # デバッグモード有効化
406
+
407
+ # どこからでもアクセス可能に
408
+
409
+ app.run(host='0.0.0.0', port=8080, threaded=True)
410
+
13
411
  ```
14
412
 
15
413
 
16
414
 
415
+ ```index.html
416
+
417
+ {% extends "layout.html" %}
418
+
419
+ {% block body %}
420
+
421
+ <body>
422
+
423
+ {% for message in get_flashed_messages() %}
424
+
425
+ <div class="alert alert-warning">
426
+
427
+ {{ message }}
428
+
429
+ </div>
430
+
431
+ {% endfor %}
432
+
433
+ <h1>在庫管理 アプリケーション</h1>
434
+
435
+ {% if session.username == "admin" %}
436
+
437
+ <table>
438
+
439
+ <tr>
440
+
441
+ <th>商品名</th>
442
+
443
+ <th>個数</th>
444
+
445
+ <th>賞味期限</th>
446
+
447
+ <th>メモ</th>
448
+
449
+ <th></th>
450
+
451
+ </tr>
452
+
453
+ {% for v in stock_list %}
454
+
455
+ <tr>
456
+
457
+ <td><a href="{{ url_for('edit', id=v['id'])}}">{{ v['name']}}</a></td>
458
+
459
+ <td>{{ v['stocknumber']}}</td>
460
+
461
+ <td>{{ v['duedate']}}</td>
462
+
463
+ <td>{{ v['memo']}}</td>
464
+
465
+ <td><a href={{ url_for("delete", id=v["id"]) }}>削除</a></td>
466
+
467
+ </tr>
468
+
469
+ {% endfor %}
470
+
471
+ </table>
472
+
473
+ <h3><a href="{{ url_for('add_stock')}}">在庫の追加</a></h3>
474
+
475
+ <h3><a href="{{ url_for('logout')}}">ログアウト</a></h3>
476
+
477
+ {% else %}
478
+
479
+ <h3><a href="{{ url_for('login')}}">ログイン</a></h3>
480
+
481
+ {% endif %}
482
+
483
+ </body>
484
+
485
+ {% endblock %}
486
+
17
487
  ```
488
+
489
+
490
+
491
+ ```edit.html
492
+
493
+ {% extends "layout.html" %}
494
+
495
+ {% block body %}
496
+
497
+ <body>
498
+
499
+
500
+
501
+ <h1>在庫を編集する</h1>
502
+
503
+
504
+
505
+ <form method="post" action="{% if type == "add" %}{{ url_for('add_stock') }}{% else %}{{ url_for('update_stock', id=stockpile["id"]) }}{% endif %}">
506
+
507
+ {% if error_list %}
508
+
509
+ <ul>
510
+
511
+ {% for v in error_list %}
512
+
513
+ <li>{{ v }}</li>
514
+
515
+ {% endfor %}
516
+
517
+ </ul>
518
+
519
+ {% endif %}
520
+
521
+ <p>商品名<br/><input type="text" name="name" value="{{ stockpile['name'] }}"/></p>
522
+
523
+ <p>在庫数<br/><input type="int" name="stocknumber" value="{{ stockpile['stocknumber'] }}"/></p>
524
+
525
+ <p>期限<br/><input type="text" name="duedate" value="{{ stockpile['duedate'] }}"/></p>
526
+
527
+ <p>メモ<br/><input type="text" name="memo" value="{{ stockpile['memo'] }}" size="60"/></p>
528
+
529
+ {% if type == "add" %}
530
+
531
+ <button type="submit">在庫を追加</button>
532
+
533
+ {% else %}
534
+
535
+ <button type="submit">在庫を更新</button>
536
+
537
+ {% endif %}
538
+
539
+ </form>
540
+
541
+ <br/>
542
+
543
+ <a href="{{ url_for('index')}}">トップに戻る</a>
544
+
545
+ </body>
546
+
547
+ {% endblock %}
548
+
549
+ ```
550
+
551
+
552
+
553
+ 調べてみた限りではredisを利用してsessionをデータベースに保存するのがいいようなことはわかったのですが、Railsでのやり方や、英語のドキュメントしか見当たらず、理解することができませんでした。
554
+
555
+
556
+
557
+ ご教示いただけると幸いです。