回答編集履歴

1

flash表示を追加

2020/02/18 03:43

投稿

FiroProchainezo
FiroProchainezo

スコア2421

test CHANGED
@@ -13,3 +13,113 @@
13
13
 
14
14
 
15
15
  (少なくともChromeで実行した場合は)そのif文はTrueになることがないと思います。
16
+
17
+
18
+
19
+
20
+
21
+ ### 2020/02/18 12:40追加
22
+
23
+
24
+
25
+ ```html
26
+
27
+ <!-- templates/index.html -->
28
+
29
+ <!DOCTYPE html>
30
+
31
+ <html lang="en">
32
+
33
+ <head>
34
+
35
+ <meta charset="UTF-8">
36
+
37
+ <title>Upload new File</title>
38
+
39
+ </head>
40
+
41
+ <body>
42
+
43
+ {% with messages = get_flashed_messages() %}
44
+
45
+ {% if messages %}
46
+
47
+ {% for message in messages %}
48
+
49
+ <p>{{ message }}</p>
50
+
51
+ {% endfor %}
52
+
53
+ {% endif %}
54
+
55
+ {% endwith %}
56
+
57
+ <h1>Upload new File</h1>
58
+
59
+ <form method=post enctype=multipart/form-data>
60
+
61
+ <input type=file name=file>
62
+
63
+ <input type=submit value=Upload>
64
+
65
+ </form>
66
+
67
+ </body>
68
+
69
+ </html>
70
+
71
+ ```
72
+
73
+
74
+
75
+ ```python
76
+
77
+ # app.py
78
+
79
+ # render_templateを読み込み
80
+
81
+ from flask import Flask, flash, request, redirect, url_for, render_template
82
+
83
+
84
+
85
+ # 中略
86
+
87
+ @app.route('/', methods=['GET', 'POST'])
88
+
89
+ def upload_file():
90
+
91
+ if request.method == 'POST':
92
+
93
+ # check if the post request has the file part
94
+
95
+ if 'file' not in request.files:
96
+
97
+ flash('No file part')
98
+
99
+ return render_template('index.html')
100
+
101
+ file = request.files['file']
102
+
103
+ # if user does not select file, browser also
104
+
105
+ # submit an empty part without filename
106
+
107
+ if file.filename == '':
108
+
109
+ flash('No selected file')
110
+
111
+ return render_template('index.html')
112
+
113
+ if file and allowed_file(file.filename):
114
+
115
+ filename = secure_filename(file.filename)
116
+
117
+ file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
118
+
119
+ return redirect(url_for('uploaded_file',
120
+
121
+ filename=filename))
122
+
123
+ return render_template('index.html')
124
+
125
+ ```