개발일지/웹개발

Flask 기초

E-room 2022. 7. 6. 23:18
728x90

Flask 서버를 만들 때,

 

프로젝트 폴더 안에

ㄴstatic 폴더 (이미지, css파일을 넣어둡니다)

ㄴtemplates 폴더 (html파일을 넣어둡니다)

ㄴapp.py 파일

 

이렇게 세 개를 만들어두고 시작한다.

 

HTML 파일 불러오기

    1. index.html 파일을 templates 폴더 안에 만든다. 아래 코드를 붙여 넣는다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Document</title>

    <script>
        function hey(){
            alert('안녕!')
        }
    </script>
</head>
<body>
    <button onclick="hey()">나는 버튼!</button>
</body>
</html>

    2. flask 내장함수 render_template를 이용하여 html 파일을 불러온다. 아래 코드를 app.py에 붙여 넣는다.

from flask import Flask, render_template
app = Flask(__name__)

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

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)

    3. app.py를 실행하여 서버를 구동시키고 접속해보면 위의 html파일이 나온다.

728x90