1
3

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で簡単にログイン・新規登録システムを作成する方法

Posted at

はじめに

Webアプリケーションを開発する際に、ログイン機能や新規登録機能は非常に重要な要素です。本記事では、PythonとHTMLを使ってシンプルなログインおよび新規登録システムを作成する方法を紹介します。これを活用すれば、フルスクラッチで簡単な認証システムを構築できます。

必要な準備

まずは、必要なライブラリをインストールしましょう。

pip install Flask

Flaskは、Pythonで簡単にWebアプリケーションを作成できる軽量なフレームワークです。

プロジェクトの構成

プロジェクトのディレクトリ構造は以下のようになります。

/project_folder
    /templates
        login.html
        register.html
        result.html
    app.py

Pythonコード (app.py)

まずは、Flaskを使用してサーバーサイドの処理を行うためのPythonコードを作成します。

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

app = Flask(__name__)

# サンプルのユーザー情報
users = {
    "user1": "password1",
    "user2": "password2"
}

@app.route('/')
def home():
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']

    # ユーザー認証
    if username in users and users[username] == password:
        return render_template('result.html', message=f"Welcome, {username}!")
    else:
        return render_template('result.html', message="Login failed. Please check your username and password.")

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # ユーザーが既に存在しないかチェック
        if username in users:
            return render_template('result.html', message="Username already exists. Please choose a different username.")

        # 新しいユーザーを登録
        users[username] = password
        return render_template('result.html', message="Registration successful! You can now log in.")

    return render_template('register.html')

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

ログイン画面 (templates/login.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>
    <h2>ログイン</h2>
    <form action="{{ url_for('login') }}" method="post">
        <label for="username">ユーザー名:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="password">パスワード:</label><br>
        <input type="password" id="password" name="password"><br><br>
        <input type="submit" value="ログイン">
    </form>
    <br>
    <a href="{{ url_for('register') }}">新規登録はこちら</a>
</body>
</html>

新規登録画面 (templates/register.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>
    <h2>新規登録</h2>
    <form action="{{ url_for('register') }}" method="post">
        <label for="username">ユーザー名:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="password">パスワード:</label><br>
        <input type="password" id="password" name="password"><br><br>
        <input type="submit" value="登録">
    </form>
    <br>
    <a href="{{ url_for('home') }}">ログインはこちら</a>
</body>
</html>

結果表示画面 (templates/result.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>
    <h2>{{ message }}</h2>
    <br>
    <a href="{{ url_for('home') }}">ログイン画面に戻る</a>
</body>
</html>

実行方法

  1. 必要なファイルを作成し、app.pyを実行します。
python app.py
  1. ブラウザでhttp://127.0.0.1:5000/にアクセスし、ログイン画面が表示されることを確認します。

画面表示

スクリーンショット 2024-08-22 17.43.42.png

スクリーンショット 2024-08-22 17.43.51.png

まとめ

このシンプルなログイン・新規登録システムは、Flaskを使ったWebアプリケーション開発の基礎を学ぶのに最適です。もちろん、実際のプロジェクトではデータベースとの連携が必須ですが、このコードはその第一歩として理解を深めるために役立つでしょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?