본문 바로가기
Research/Network

flask_서버 세팅 및 간단한 html 렌더링하기

by RIEM 2022. 11. 22.

4-2. Flask 시작하기 - 서버만들기

flask 프레임워크 사용해서 서버 구축할 것임. 우선 flask 설치 필요.

기본 flask 서버 프로젝트 디렉토리 구조는 아래와 같다

>app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
  return 'This is Home!'

@app.route('/mypage')
def mypage():
  return 'This is My Page!'

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

 

요렇게 하고 파일을 실행시키면, 브라우저에서 로컬 환경 서버로 접근할 수 있다.

app.py에서 명시한 route로 접근하게 되면 각각의 함수가 실행된다. 그 함수의 리턴값을 웹사이트에 렌더링해주는 것으로 보인다.

 

4-3 Flask 시작하기 - HTML 파일 주기

render_template를 import해서 사용해주자.

함수에서 return 값 대신 render_template()를 반환한다. 이때 아규먼트를 ‘index.html’를 주게되면, 해당 경로의 사이트에 접속할 경우 index.html 화면을 볼 수 있다.

app.py

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

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

@app.route('/mypage')
def mypage():
  return 'This is My Page!'

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

 

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
      function hey() {
          $.ajax({
              type: "POST",
              url: "/test",
              data: {title_give: '봄날은간다'},
              success: function (response) {
                  console.log(response)
              }
          })
      }
  </script>
</head>
<body>
<h1>My first page ;)</h1>
<button onclick="hey()">Click</button>
</body>
</html>

 

댓글