본문 바로가기
Coding/Python

[Python & Flask] 플라스크를 이용하여 html과 간단하게 호출하는 방법 !!

by 포스트it 2023. 10. 26.
반응형

 

[Python & Flask] 플라스크를 이용하여 html과 간단하게 호출하는 방법 !!

폴더 구조는 아래와 같이 해주시면 됩니다 ㅎ

Project
 ㄴ templates
       ㄴ index.html
 ㄴ app.py

파이썬 코드
from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/button_click", methods=["POST"])
def button_click():
    # 버튼 클릭 시 실행될 로직
    print("버튼이 클릭되었습니다!")
    return jsonify({"message": "버튼이 클릭되었습니다!"})

if __name__ == "__main__":
    app.run(debug=True, port=5111)
HTML 코드
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Button Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <button id="myButton">클릭하세요!</button>

    <script>
        $(document).ready(function () {
            $("#myButton").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/button_click",
                    success: function (response) {
                        alert(response.message);
                    },
                    error: function (error) {
                        console.log(error);
                        alert("버튼 클릭 처리 중 에러가 발생했습니다.");
                    }
                });
            });
        });
    </script>
</body>
</html>
728x90
반응형

댓글