ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [3월 5주차-3/31]🐍 Flask로 로그인 시스템 만들기 - 기초부터 실습까지!
    Why Not SW CAMP 5기/수업 기록 2025. 3. 31. 17:38

    안녕하세요! 이번 글에서는 Python의 마이크로 웹 프레임워크인 Flask를 사용해 간단한 로그인 시스템을 직접 만들어보는 과정을 정리해보았습니다.
    입문자도 따라할 수 있도록 구성했으며, HTML + Flask + 간단한 로직만으로도 꽤 실전 같은 흐름을 만들어볼 거예요.


    🧱 프로젝트 구조

    먼저 프로젝트 폴더 구조를 간단히 살펴볼게요:

    work_flask/
    ├── routes.py                   # 메인 Flask 앱 라우팅
    └── templates/                  # HTML 템플릿 폴더
        ├── login.html              # 로그인 페이지
        └── hello.html              # 로그인 성공 페이지
    

    🧠 핵심 기능

    • 아이디/비밀번호 딕셔너리 기반 로그인
    • 관리자(admin) 유저는 별도 페이지로 이동
    • 로그인 실패 시 에러 메시지 표시 + 다시 입력 UI
    • HTML + Bootstrap + JavaScript 조합

    📜 routes.py 코드

    from flask import Flask, render_template, redirect, url_for, request
    
    app = Flask(__name__)
    
    users = {
        'admin': '1234',
        'rubi': '1111',
        'kara': '2222',
    }
    
    @app.route('/')
    def index():
        return render_template('login.html')
    
    @app.route('/admin')
    def admin():
        return 'Admin page'
    
    @app.route('/success/<name>')
    def success(name):
        if name == 'admin':
            return redirect(url_for('admin'))
        return render_template('hello.html', name=name)
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']
            if username in users and users[username] == password:
                return redirect(url_for('success', name=username))
            else:
                error = '❌ 로그인 실패!<br><small>아이디 또는 비밀번호를 확인하세요.</small>'
                return render_template('login.html', error=error)
        return render_template('login.html')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    🖥️ login.html

    로그인 화면 / 로그인 실패 화면

    <!-- templates/login.html -->
    <!DOCTYPE html>
    <html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>로그인</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body {
                background-color: #f8fafc;
                height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .login-box {
                background: white;
                padding: 3rem;
                border-radius: 1rem;
                box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
                width: 400px;
            }
        </style>
    </head>
    <body>
        <div class="login-box text-center">
            <h3 class="mb-4">🔐 로그인</h3>
    
            {% if error %}
                <!-- 에러 메시지 UI -->
                <div id="error-section">
                    <div class="alert alert-danger">{{ error|safe }}</div>
                    <button class="btn btn-outline-secondary" onclick="showLoginForm()">다시 입력하기</button>
                </div>
            {% endif %}
    
            <!-- 로그인 폼 UI -->
            <form id="login-form" action="/login" method="post" {% if error %}style="display: none;"{% endif %}>
                <div class="mb-3 text-start">
                    <label for="username" class="form-label">아이디</label>
                    <input type="text" class="form-control" id="username" name="username" required>
                </div>
                <div class="mb-3 text-start">
                    <label for="password" class="form-label">비밀번호</label>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>
                <button type="submit" class="btn btn-primary w-100">로그인</button>
            </form>
        </div>
    
        <script>
            function showLoginForm() {
                // 에러 메시지 숨기고 input 폼 다시 보여줌
                document.getElementById('error-section').style.display = 'none';
                document.getElementById('login-form').style.display = 'block';
            }
        </script>
    </body>
    </html>

    👋 hello.html

    <!--hello.html-->
    
    <!-- templates/hello.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Hello {{ name or 'Guest' }}</title>
        <!-- Bootstrap CSS CDN -->
        <style>
            body {
                background-color: #f7f9fc;
                display: flex;
                align-items: center;
                justify-content: center;
                height: 100vh;
            }
            .hello-box {
                background-color: white;
                padding: 3rem 4rem;
                border-radius: 1rem;
                box-shadow: 0 0 15px rgba(0,0,0,0.1);
                text-align: center;
            }
            .hello-box h1 {
                font-weight: 700;
                color: #007bff;
            }
            .hello-box p {
                color: #666;
            }
        </style>
    </head>
    <body>
        <div class="hello-box">
             <h1>👋 Hello, {{ name }}!</h1>
            <p>로그인에 성공하셨습니다.</p>
            <a href="/" class="btn btn-secondary mt-3">로그아웃</a>
        </div>
    </body>
    </html>
     

    ✅ 마무리

    이제 단순한 로그인 기능을 구현해봤어요!
    딕셔너리, 조건문, redirect, 에러 메시지, 템플릿 변수 활용 등 Flask의 기초 개념을 꽉 잡을 수 있는 예제였습니다.

     

     

Designed by Tistory.