1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonとHTMLで簡単な掲示板を作ろう:Flaskで始めるWebアプリ開発入門

Last updated at Posted at 2024-07-22

はじめに

PythonとHTMLを使って簡単な掲示板アプリケーションを作成してみましょう。このチュートリアルでは、Pythonの軽量WebフレームワークであるFlaskを使って、基本的な掲示板を構築します。掲示板のフロントエンドにはHTMLを使用します。

ディレクトリ構造

まず、以下のようなディレクトリ構造を作成します。

message_board/
│
├── app.py
└── templates/
    └── index.html

必要なライブラリのインストール

Flaskをインストールしていない場合は、以下のコマンドでインストールします。

pip install flask

Flaskアプリケーションの作成

app.pyファイルを作成し、以下のコードを記述します。

app.py
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# メッセージを保存するリスト
messages = []

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # フォームからメッセージを取得
        message = request.form.get('message')
        if message:
            messages.append(message)
        return redirect(url_for('index'))
    
    return render_template('index.html', messages=messages)

if __name__ == '__main__':
    app.run(debug=True)

コードの説明

1.Flaskのインポートとアプリケーションの作成:

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

Flaskモジュールをインポートし、Flaskアプリケーションのインスタンスを作成します。

2.メッセージの保存:

messages = []

投稿されたメッセージを保存するためのリストを定義します。

3.ルートの設定:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # フォームからメッセージを取得
        message = request.form.get('message')
        if message:
            messages.append(message)
        return redirect(url_for('index'))
    
    return render_template('index.html', messages=messages)
  • /ルートを定義し、GETおよびPOSTリクエストを処理します。
  • POSTリクエストが送信された場合、フォームからメッセージを取得し、messagesリストに追加します。
  • メッセージを追加した後、リダイレクトしてページを更新します。
  • GETリクエストの場合、メッセージを含むテンプレートをレンダリングします。

4.アプリケーションの実行:

if __name__ == '__main__':
    app.run(debug=True)

スクリプトが直接実行された場合、Flask開発サーバーを起動します。

HTMLテンプレートの作成

次に、templatesフォルダにindex.htmlファイルを作成し、以下のコードを記述します。

templates/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>掲示板</title>
</head>
<body>
    <h1>簡単な掲示板</h1>
    <form method="POST" action="/">
        <textarea name="message" rows="4" cols="50" placeholder="メッセージを入力してください"></textarea><br>
        <button type="submit">投稿</button>
    </form>
    <h2>投稿一覧</h2>
    <ul>
        {% for message in messages %}
            <li>{{ message }}</li>
        {% endfor %}
    </ul>
</body>
</html>

アプリケーションの実行

上記のファイルを作成したら、ターミナルでアプリケーションを実行します。

python app.py

次に、ブラウザで http://127.0.0.1:5000/ にアクセスすると、掲示板が表示されます。メッセージを入力して投稿すると、ページがリロードされてメッセージがリストに追加されます。

画面表示結果

スクリーンショット 2024-07-22 17.25.46.png

終わりに

このチュートリアルでは、PythonのFlaskフレームワークとHTMLを使って簡単な掲示板を作成しました。次のステップとして、データベースを導入してメッセージを永続化する方法や、ユーザー認証機能を追加してみるのも良いでしょう。ぜひ、挑戦してみてください!

1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?