0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

flaskでシンプルな掲示板を実装した

Last updated at Posted at 2025-01-02

実際に動かしてみるとこんな感じ
post.png

app.py

app.py
from flask import Flask, render_template, request

app = Flask(__name__)

posts = []
    
@app.route("/", methods = ["GET", "POST"])
def index():
    if request.method == "POST":
        new_post_data = {
                "name": request.form["name"],
                "text": request.form["text"],
        }
        posts.append(new_post_data)
    return render_template("index.html", posts = posts)
app.run()

/はGETとPOSTを受け付ける POSTが送られた場合は連想配列new_post_dataに投稿者の名前と投稿内容を格納する その後配列postsに格納する

関数の最後はrender_templateでindex.htmlを返して配列postsを渡す

templates/index.html

templates/index.html
<html>
	<body>
		{% for x in posts%}
		<p>name: {{ x["name"] }}</p>
		<p>text: {{ x["text"] }}</p>
		{% endfor %}
		<form action="/" method="post">
			<input name="name" type="name">
			<br>
			<textarea name="text">
			</textarea>
			<button type="submit">
		</form>
	</body>
</html>

前述の渡された配列postsをfor文で描画する 名前と投稿内容を連想配列から取り出して描画している

formタグで投稿フォームを作っている buttonタグをクリックすると投稿される

postメソッドとは(MDNより引用)

HTTP の POST メソッドは、サーバーにデータを送信します。リクエストの本文の型は Content-Type ヘッダーで示されます。

PUT と POST との違いは、 PUT がべき等であることです。一度呼び出しても複数回呼び出しても成功すれば同じ効果になる(副作用がない)のに対して、同じ POST に成功すると、複数回の注文を行うような、追加の効果が出ます。

POST リクエストは、ふつう HTML フォームを介して送信され、サーバーに変化をもたらします。この場合、

要素の enctype 属性や または 要素の formenctype 属性に適切な文字列が指定することで、コンテンツタイプを選択することができます。
引用元:
参考
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?