로그인 회원가입
모두인포
전체IT경제사회생활스포츠시사여행연애

Python Flask 기본 게시판 예제

lmkfox · 2025-05-17 · 조회 0
Python Flask 기본 게시판 예제
1. 프로젝트 구조 flask_board/ ├── app.py ├── templates/ │ ├── index.html │ ├── post.html │ ├── new.html ├── static/ │ └── style.css └── board.db (자동 생성됨) 2. 패키지 설치 및 환경 설정 pip install flask flask_sqlalchemy 3.  app.py  - Flask 애플리케이션 메인 코드 from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///board.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # 모델 정의 class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) date = db.Column(db.DateTime, default=datetime.datetime.utcnow) # DB 생성 with app.app_context(): db.create_all() # 게시글 목록 @app.route('/') def index(): posts = Post.query.order_by(Post.date.desc()).all() return render_template('index.html', posts=posts) # 게시글 작성 폼 @app.route('/new') def new(): return render_template('new.html') # 게시글 저장 @app.route('/create', methods=['POST']) def create(): title = request.form['title'] content = request.form['content'] new_post = Post(title=title, content=content) db.session.add(new_post) db.session.commit() return redirect(url_for('index')) # 게시글 상세 보기 @app.route('/post/<int:id>') def post(id): post = Post.query.get_or_404(id) return render_template('post.html', post=post) # 게시글 삭제 @app.route('/delete/<int:id>') def delete(id): post = Post.query.get_or_404(id) db.session.delete(post) db.session.commit() return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True) 4. 템플릿 파일 templates/index.html <!DOCTYPE html> <html> <head> <title>게시판</title> </head> <body> <h1>게시판</h1> <a href="{{ url_for('new') }}">새 글 작성</a> <ul> {% for post in posts %} <li> <a href="{{ url_for('post', id=post.id) }}">{{ post.title }}</a> - {{ post.date.strftime('%Y-%m-%d %H:%M') }} </li> {% endfor %} </ul> </body> </html> templates/new.html <!DOCTYPE html> <html> <head> <title>새 글 작성</title> </head> <body> <h1>새 글 작성</h1> <form method="POST" action="{{ url_for('create') }}"> 제목: <input type="text" name="title" required><br> 내용: <br><textarea name="content" rows="10" cols="50" required></textarea><br> <button type="submit">등록</button> </form> <a href="{{ url_for('index') }}">목록으로</a> </body> </html> templates/post.html <!DOCTYPE html> <html> <head> <title>{{ post.title }}</title> </head> <body> <h1>{{ post.title }}</h1> <p>{{ post.content }}</p> <p>작성일: {{ post.date.strftime('%Y-%m-%d %H:%M') }}</p> <a href="{{ url_for('delete', id=post.id) }}">삭제</a> | <a href="{{ url_for('index') }}">목록으로</a> </body> </html> 5. 실행 python app.py http://localhost:5000 접속 후 게시판 이용 가능 추가 기능 제안 - 게시글 수정 기능 - 댓글 기능 - 사용자 로그인 연동 - Markdown 지원 - 페이징 처리

댓글

아직 댓글이 없습니다.

로그인 후 댓글을 남길 수 있습니다.