👩‍💻 Develope/Python

[Flask] 메시지 플래싱 (Message Flashing)

heywantodo 2023. 7. 15. 17:44
728x90
반응형

[Flask] 메시지 플래싱 (Message Flashing)

플라스크는 플래싱 시스템을 가지고 사용자에게 피드백을 주는 간단한 방법을 제공한다.

즉, 플래싱이란 서버에서 처리하며 생긴 오류사항/처리사항을 HTML에 넘겨 줄 수 있는 기능을 말한다.

 

만약 사용자가 로그인 정보를 입력하지 않았을 때, 피드백을 보내고싶다고하면 다음과 같이 작성할 수 있다.

입력받은 정보의 길이가 0이라면 flash 메시지를 보내도록 한다. 

if len(username) == 0 or len(password) == 0:
  flash("ID 또는 PASSWORD를 입력하세요")
  return redirect('/login')

HTML에선 다음과 같이 작성해준다.

body 태그 안에 넣어주면 된다. 

<body>
    {% with messages = get_flashed_messages() %}
        {% if messages %}
          {{ messages[-1] }}
        {% endif %}
    {% endwith %}
</body>

조건에 부합하면 메시지를 출력한다. 

메시지 형식이 아닌 alert으로 출력하고 싶다면, 이것 또한 매우 간단하다.

    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <script>
              alert("{{ messages[-1] }}")
            </script>
        {% endif %}
    {% endwith %}

나는 기본 alert 창이 너무 못생겨서 custom을 찾아보니 좋은 자료가 있었다.

https://www.ondiek-elijah.me/blog/custom-alerts-in-flask-using-sweetalert2

 

Custom Alerts in Flask Using SweetAlert2

This article describes how to use Sweetalert2 to create custom alerts in Flask Jinja templates. Learn how to display alerts in a way that users will appreciate.

www.ondiek-elijah.me

head안에 css의 링크를 넣어주고

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{{ url_for('static', filename='login.css') }}">
    <link
            href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
            rel="stylesheet"
            integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
            crossorigin="anonymous"
    />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <title>Login</title>
</head>

코드를 수정해주면 끝

<body>
    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <script>
                Swal.fire({
                    text: '{{ messages[-1] }}'
                })
            </script>
        {% endif %}
    {% endwith %}
</body>

예쁜 alert 창~

참고

https://wikidocs.net/167068

https://scribblinganything.tistory.com/399

728x90
반응형