質問編集履歴

1

ソースコードを追記

2023/11/03 02:10

投稿

yasuuu
yasuuu

スコア9

test CHANGED
File without changes
test CHANGED
@@ -24,7 +24,99 @@
24
24
  from flask.globals import _request_ctx_stack
25
25
  ImportError: cannot import name '_request_ctx_stack' from 'flask.globals' (/Users/xxxxx/flaskbook/venv/lib/python3.12/site-packages/flask/globals.py)
26
26
  ```
27
+ ### ソースコード
28
+ ```
29
+ import logging
30
+ from email_validator import validate_email, EmailNotValidError
31
+ from flask import (
32
+ Flask,
33
+ render_template,
34
+ url_for,
35
+ current_app,
36
+ g,
37
+ request,
38
+ redirect,
39
+ flash
40
+ )
41
+ from flask_debugtoolbar import DebugToolbarExtension
27
42
 
43
+ app = Flask(__name__)
44
+ app.config["SECRET_KEY"] = "2AZSMss3p5QPbcY2hBsJ"
45
+ app.logger.setLevel(logging.DEBUG)
46
+ app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
47
+ toolbar = DebugToolbarExtension(app)
48
+
49
+
50
+ @app.route("/")
51
+ def index():
52
+ return "Hello, Flaskbook!"
53
+
54
+
55
+ @app.route("/hello/<name>", methods=["GET", "POST"], endpoint="hello-endpoint")
56
+ def hello(name):
57
+ return f"Hello, {name}!"
58
+
59
+
60
+ @app.route("/name/<name>")
61
+ def show_name(name):
62
+ return render_template("index.html", name=name)
63
+
64
+
65
+ @app.route("/contact")
66
+ def contact():
67
+ return render_template("contact.html")
68
+
69
+
70
+ @app.route("/contact/complete", methods=["GET", "POST"])
71
+ def contact_complete():
72
+ if request.method == "POST":
73
+ username = request.form["username"]
74
+ email = request.form["email"]
75
+ description = request.form["description"]
76
+
77
+ is_valid = True
78
+
79
+ if not username:
80
+ flash("ユーザ名は必須です")
81
+ is_valid = False
82
+
83
+ if not email:
84
+ flash("メールアドレスは必須です")
85
+ is_valid = False
86
+
87
+ try:
88
+ validate_email(email)
89
+ except EmailNotValidError:
90
+ flash("メールアドレスの形式で入力してください")
91
+ is_valid = False
92
+
93
+ if not description:
94
+ flash("問い合わせ内容は必須です")
95
+ is_valid = False
96
+
97
+ if not is_valid:
98
+ return redirect(url_for("contact"))
99
+
100
+ # メールを送る(最後に実装)
101
+
102
+ flash("問い合わせ内容はメールにて送信されました。問い合わせありがとうございます。")
103
+ return redirect(url_for("contact_complete"))
104
+
105
+ return render_template("contact_complete.html")
106
+
107
+
108
+ with app.test_request_context():
109
+ # /
110
+ print(url_for("index"))
111
+ # /hello/world
112
+ print(url_for("hello-endpoint", name="world"))
113
+ # /name/ichiro?page=1
114
+ print(url_for("show_name", name="ichiro", page=1))
115
+
116
+
117
+ with app.test_request_context("/users?updated=true"):
118
+ print(request.args.get("updated"))
119
+ ```
28
120
 
29
121
 
30
122
  ### 補足情報(FW/ツールのバージョンなど)