Flask에서 사용자 프로필 페이지 만들기
이전 글에서는 Flask와 Bootstrap을 활용하여 UI를 개선하는 방법을 배웠습니다.
이번 글에서는 사용자 프로필 페이지를 만들어보겠습니다.
✅ 사용자 정보 표시 (이름, 가입일 등)
✅ 비밀번호 변경 기능 추가
✅ 프로필 편집 기능 구현
[PYTHON] Flask와 Bootstrap을 활용한 UI 개선
Flask와 Bootstrap을 활용한 UI 개선 이전 글에서는 Flask를 이용한 로그인 기능을 구현했습니다.이번 글에서는 Flask와 Bootstrap을 활용하여웹 애플리케이션의 **UI(User Interface, 사용자 인터페이스)**를
englishforkid.tistory.com
1. 데이터베이스에 프로필 정보 추가
먼저, 기존의 users 테이블에 프로필 정보를 추가하겠습니다.
📌 프로필 정보를 추가하는 SQL 코드 (update_db.py)
import sqlite3
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# users 테이블에 프로필 관련 컬럼 추가
cursor.execute("""
ALTER TABLE users ADD COLUMN email TEXT;
""")
cursor.execute("""
ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
""")
conn.commit()
conn.close()
✅ email → 이메일 정보 추가
✅ created_at → 가입일 저장
위 코드를 실행하여 기존 데이터베이스를 업데이트하세요.
python update_db.py
2. 사용자 프로필 페이지 만들기
📌 Flask 라우트 (app.py)
from flask import Flask, render_template, session, redirect, url_for
import sqlite3
app = Flask(__name__)
app.secret_key = "supersecretkey"
# 데이터베이스 연결 함수
def get_db_connection():
conn = sqlite3.connect("users.db")
conn.row_factory = sqlite3.Row
return conn
# 사용자 프로필 페이지
@app.route("/profile")
def profile():
if "user" not in session:
return redirect(url_for("login"))
username = session["user"]
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
return render_template("profile.html", user=user)
if __name__ == "__main__":
app.run(debug=True)
✅ session["user"] → 로그인한 사용자 정보 가져오기
✅ cursor.execute("SELECT * FROM users WHERE username = ?", (username,)) → 사용자 정보 조회
📌 프로필 페이지 템플릿 (templates/profile.html)
{% extends "base.html" %}
{% block title %}프로필{% endblock %}
{% block content %}
<div class="container">
<h2>프로필 정보</h2>
<p><strong>아이디:</strong> {{ user["username"] }}</p>
<p><strong>이메일:</strong> {{ user["email"] if user["email"] else "미등록" }}</p>
<p><strong>가입일:</strong> {{ user["created_at"] }}</p>
<a href="/edit_profile" class="btn btn-primary">프로필 수정</a>
</div>
{% endblock %}
✅ {{ user["email"] if user["email"] else "미등록" }} → 이메일이 없을 경우 "미등록" 표시
✅ 가입일 표시
3. 프로필 수정 기능 구현
📌 Flask 라우트 (app.py)
@app.route("/edit_profile", methods=["GET", "POST"])
def edit_profile():
if "user" not in session:
return redirect(url_for("login"))
username = session["user"]
conn = get_db_connection()
cursor = conn.cursor()
if request.method == "POST":
email = request.form["email"]
cursor.execute("UPDATE users SET email = ? WHERE username = ?", (email, username))
conn.commit()
conn.close()
return redirect(url_for("profile"))
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
return render_template("edit_profile.html", user=user)
✅ request.form["email"] → 사용자가 입력한 이메일 가져오기
✅ cursor.execute("UPDATE users SET email = ? WHERE username = ?", (email, username)) → 이메일 정보 업데이트
📌 프로필 수정 페이지 템플릿 (templates/edit_profile.html)
{% extends "base.html" %}
{% block title %}프로필 수정{% endblock %}
{% block content %}
<div class="container">
<h2>프로필 수정</h2>
<form method="POST">
<div class="mb-3">
<label class="form-label">이메일</label>
<input type="email" name="email" class="form-control" value="{{ user['email'] }}">
</div>
<button type="submit" class="btn btn-success">저장</button>
</form>
</div>
{% endblock %}
✅ 기존 이메일 값을 value="{{ user['email'] }}"로 설정
✅ 이메일을 입력한 후 저장을 누르면 변경됨
4. 비밀번호 변경 기능 구현
📌 Flask 라우트 (app.py)
from werkzeug.security import generate_password_hash, check_password_hash
@app.route("/change_password", methods=["GET", "POST"])
def change_password():
if "user" not in session:
return redirect(url_for("login"))
if request.method == "POST":
old_password = request.form["old_password"]
new_password = request.form["new_password"]
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT password FROM users WHERE username = ?", (session["user"],))
user = cursor.fetchone()
if user and check_password_hash(user["password"], old_password):
new_hashed_password = generate_password_hash(new_password)
cursor.execute("UPDATE users SET password = ? WHERE username = ?", (new_hashed_password, session["user"]))
conn.commit()
conn.close()
return redirect(url_for("profile"))
else:
conn.close()
return "⚠️ 현재 비밀번호가 틀렸습니다."
return render_template("change_password.html")
✅ check_password_hash(user["password"], old_password) → 현재 비밀번호 확인
✅ generate_password_hash(new_password) → 새 비밀번호 암호화
📌 비밀번호 변경 페이지 템플릿 (templates/change_password.html)
{% extends "base.html" %}
{% block title %}비밀번호 변경{% endblock %}
{% block content %}
<div class="container">
<h2>비밀번호 변경</h2>
<form method="POST">
<div class="mb-3">
<label class="form-label">현재 비밀번호</label>
<input type="password" name="old_password" class="form-control" required>
</div>
<div class="mb-3">
<label class="form-label">새 비밀번호</label>
<input type="password" name="new_password" class="form-control" required>
</div>
<button type="submit" class="btn btn-warning">비밀번호 변경</button>
</form>
</div>
{% endblock %}
✅ 현재 비밀번호와 새 비밀번호를 입력받아 변경
5. 결론
이번 글에서는 Flask에서 사용자 프로필 페이지를 만드는 방법을 배웠습니다.
- 프로필 정보 저장 (이메일, 가입일 추가)
- 사용자 프로필 조회 및 수정 기능 구현
- 비밀번호 변경 기능 추가
다음 글에서는 Flask에서 파일 업로드 및 프로필 사진 등록하는 방법을 배워보겠습니다! 🚀
[파이썬 자격증] COS Pro 자격증 활용 가이드: 취업, 경력 개발, 실무 적용까지
COS Pro 자격증 활용 가이드: 취업, 경력 개발, 실무 적용까지 COS Pro 자격증은 단순한 시험이 아니라, 프로그래밍 역량을 공식적으로 인증받는 실용적인 자격증입니다. 개발자로 취업을 준비하는
englishforkid.tistory.com
[PYTHON] Flask를 이용한 간단한 웹 애플리케이션 만들기
Flask를 이용한 간단한 웹 애플리케이션 만들기 이전 글에서는 자동 이메일 발송 기능을 구현해 보았습니다.이제 Python을 활용하여 간단한 웹 애플리케이션을 만들어 보겠습니다.웹 애플리케이
englishforkid.tistory.com
'BIG DATA > PYTHON' 카테고리의 다른 글
[PYTHON] Flask에서 이메일 인증 구현하기 (0) | 2025.03.04 |
---|---|
[PYTHON] Flask에서 파일 업로드 및 프로필 사진 등록하기 (0) | 2025.03.01 |
[PYTHON] Flask와 Bootstrap을 활용한 UI 개선 (0) | 2025.02.27 |
[PYTHON] Flask로 로그인 기능 구현하기 (세션 활용) (0) | 2025.02.27 |
[PYTHON] Flask를 이용한 간단한 웹 애플리케이션 만들기 (0) | 2025.02.24 |