끄적이는 개발노트

260415_강의 정리 (Flask) 본문

Python

260415_강의 정리 (Flask)

크런키스틱 2026. 4. 15. 19:53
728x90

■ Flask

  • jinja2
    • Python에서 사용하는 템플릿 엔진(template engine)
    • HTML을 동적으로 만듬 => data + HTML
# 기본
{{data}}

# 조건문
{% if user %}
	안녕하세요
{% endif %}

# 반복문
{% for item in list %}
	{{ item }}
{% endfor %}

 

  • 핵심 코드
    • render_template("index.html", data=data)
      • HTML + 데이터 결합 => 렌더링
      • 최종 HTML Response 생성
    • make_response(Cookie)
      • Response 객체 직접 생성
      • 쿠키 생성
      • 헤더 조작
    • jsonify()
      • Python dict => JSON Response 변환
      • Content-Type : application/json
  • html 상속 (extends 가능)
<!-- 부모 html -->
<html>
<body>
  {% block content %}{% endblock content %}
</body>
</html>

<!-- 자식 html -->
{% extends "base.html" %}

{% block content %}
	<h1>Hello</h1>
{% endblock content %}

 

 

■ Flask MVC 예제 코드

# models/user_model.py

import pymysql


def get_all_users():
    conn = pymysql.connect(...)
    try:
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM users")
            result = cursor.fetchall()
        return result
    finally:
        conn.close()


def create_user(name):
    conn = pymysql.connect(...)
    try:
        with conn.cursor() as cursor:
            cursor.execute(
                "INSERT INTO users (name) VALUES (%s)",
                (name,)
            )
        conn.commit()
    finally:
        conn.close()
# routes/user_routes.py

from flask import Blueprint, render_template, request, redirect, url_for
from models.user_model import get_all_users, create_user

user_bp = Blueprint('user', __name__)


@user_bp.route('/users')
def users():
    users = get_all_users()
    return render_template('users.html', users=users)


@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        name = request.form.get('name')
        create_user(name)
        return redirect(url_for('user.users'))

    return render_template('register.html')
# app.py

from flask import Flask
from routes.user_routes import user_bp

app = Flask(__name__)

# Blueprint 등록
app.register_blueprint(user_bp)

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

 

728x90