Programming/python(파이썬)

python flask를 이용한 static web + rest api server 구현

구차니 2025. 9. 29. 10:57

gpt와 검색을 버무려서~

 

pip로 대~~~충 flask 설치하고

Flask 에 static_url_path와 static_folder 를 설정해서 정적으로 서빙할 경로를 지정한다.

template_folder는 template engine를 위한 경로 같긴한데, 지금은 그걸 하려는게 아니니 패스~ 하고

 

/ 로 요청이 들어오면 index.html을 던지도록 라우터 하나 설정하고

나머지는 자동으로 static 경로 하위에서 제공

그리고 /api 쪽은 별도로 라우터 지정해서 2개의 api를 생성해준다.

 

/app.py

from flask import Flask, jsonify, render_template

app = Flask(__name__,
            static_url_path='', 
            static_folder='static',
            template_folder='templates')

@app.route('/')
def serve_index():
    return app.send_static_file('index.html')

# REST API 라우트
@app.route('/api/hello')
def api_hello():
    return jsonify({"message": "Hello, this is a REST API response!"})

# 또 다른 REST API
@app.route('/api/sum/<int:a>/<int:b>')
def api_sum(a, b):
    return jsonify({"a": a, "b": b, "sum": a + b})


if __name__ == "__main__":
    # 디버그 모드 실행
    app.run(debug=True)

 

/static/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello Flask</h1>
    <p>이 페이지는 Flask가 제공하는 정적 웹입니다.</p>

    <button onclick="callApi()">API 호출</button>
    <p id="result"></p>

    <script>
        async function callApi() {
            const res = await fetch("/api/hello");
            const data = await res.json();
            document.getElementById("result").innerText = data.message;
        }
    </script>
</body>
</html>

 

/static/test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>this is test</h1>
</body>
</html>

 

/static/style.css

body {
    font-family: sans-serif;
    background: #f0f0f0;
    padding: 20px;
}
h1 {
    color: darkblue;
}

 

[링크 : https://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask]

 

 

$ python3 app.py
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 997-788-229

 

웹에서 접속하면 아래처럼 뜨는데

보니 template 엔진을 이용해서 치환하도록 해놨어서 css가 안 읽혔군

127.0.0.1 - - [29/Sep/2025 10:48:26] "GET / HTTP/1.1" 304 -
127.0.0.1 - - [29/Sep/2025 10:48:26] "GET /{{%20url_for('static',%20filename='style.css')%20}} HTTP/1.1" 404 -

 

그럼 template 안쓸꺼니 수정해보자

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Hello Flask</h1>
    <p>이 페이지는 Flask가 제공하는 정적 웹입니다.</p>

    <button onclick="callApi()">API 호출</button>
    <p id="result"></p>

    <script>
        async function callApi() {
            const res = await fetch("/api/hello");
            const data = await res.json();
            document.getElementById("result").innerText = data.message;
        }
    </script>
</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>this is test</h1>
</body>
</html>

 

이쁘게 잘나온다. 그런데 처음 접속하면 static web이라도 제법 느린데 캐싱이 안되나?

 

localhost:5000/

localhost:5000/index.html

localhost:5000/test.html

localhost:5000/api/hello

localhost:5000/api/sum/2/3