파이썬의 마이크로 웹 프레임워크 중 Flask를 예로 들어 구조와 간단한 코드 예제를 설명해 드리겠습니다. Flask는 간단하면서도 유연성이 뛰어난 프레임워크로, 웹 애플리케이션 개발에 매우 적합합니다.

Flask 구조

Flask 애플리케이션의 기본 구조는 다음과 같습니다:

my_flask_app/
│
├── app.py         # 메인 애플리케이션 파일
├── templates/     # HTML 템플릿 파일
│   └── index.html
├── static/        # 정적 파일 (CSS, JS, 이미지 등)
│   ├── styles.css
│   └── script.js
└── requirements.txt # 필요한 패키지 목록

예제 코드

아래는 Flask로 간단한 웹 애플리케이션을 만드는 예제입니다.

1. app.py

from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/about')
def about():
    return '<h1>About Page</h1>'

if __name__ == '__main__':
    app.run(debug=True)

2. templates/index.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    <title>Flask 예제</title>
</head>
<body>
    <h1>환영합니다!</h1>
    <p><a href="/about">About 페이지</a></p>
</body>
</html>

3. static/styles.css

body {
    font-family: Arial, sans-serif;
    margin: 20px;
}

h1 {
    color: #333;
}

a {
    text-decoration: none;
    color: #007BFF;
}

실행 방법

  1. 필요한 패키지 설치: requirements.txt 파일을 만들고 다음 내용을 추가합니다.

    Flask

    그런 다음, 아래 명령어로 패키지를 설치합니다.

    pip install -r requirements.txt
  2. 애플리케이션 실행: 아래 명령어로 Flask 애플리케이션을 실행합니다.

    python app.py
  3. 웹 브라우저에서 접속: 웹 브라우저를 열고 http://127.0.0.1:5000/로 접속하면 "환영합니다!"라는 메시지가 보이고, "About 페이지" 링크를 클릭하면 About 페이지로 이동합니다.

이렇게 Flask를 사용하여 간단한 웹 애플리케이션을 만들어볼 수 있습니다. 더 복잡한 기능이나 추가적인 질문이 있으시면 말씀해 주세요!

+ Recent posts