반응형
    
    
    
  사전준비
- Python 설치
 - Flask 설치
- pip install Flask(win)
 - pip3 install Flask(mac)
 
 - MySQL 서버 및 클라이언트 설치
 - Database, User, Table 추가
 - Flask-MySQL 설치
- pip install Flask-MySQL(win)
 - pip3 install Flask-MySQL(mac)
 
 - Bootstrap CSS 및 JavaScript 파일
- CDN 링크를 사용하거나 프로젝트에 직접 다운로드
 
 
Database, User, Table 추가
아래 링크를 참고하여 디비, 사용자, 테이블을 추가
mysql 사용자 추가, DB 생성, 권한부여
root 계정으로 mysql 접속하기 mysql -u root -p mysql 데이터베이스 선택 mysql 데이터베이스에 계정/디비/권한 등의 정보가 저장됩니다. use mysql; 사용자(+권한) 추가 # create user db_user_id@localhost identified by '
web.todaycoding.com
테이블은 아래 참조
CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT
);
Flask 생성 및 MySQL 연결
파일명으로 "app.py" 설정하고 아래 소스를 붙여넣는다.
코드에서 "your_~~" 부분은
디비 정보를 입력합니다.
from flask import Flask, render_template, request, redirect, url_for
from flaskext.mysql import MySQL
app = Flask(__name__)
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = 'your_username'
app.config['MYSQL_DATABASE_PASSWORD'] = 'your_password'
app.config['MYSQL_DATABASE_DB'] = 'your_database_name'
mysql = MySQL(app)
@app.route('/')
def index():
    cursor = mysql.get_db().cursor()
    cursor.execute('SELECT * FROM items')
    items = cursor.fetchall()
    return render_template('index.html', items=items)
@app.route('/add', methods=['POST', 'GET'])
def add():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
    
        cursor = mysql.get_db().cursor()
        cursor.execute('INSERT INTO items(name, description) VALUES (%s, %s)', (name, description))
        mysql.get_db().commit()
    
        return redirect(url_for('index'))
    else:
        return render_template('add.html')
@app.route('/edit/<int:id>')
def edit(id):
    cursor = mysql.get_db().cursor()
    cursor.execute('SELECT * FROM items WHERE id=%s', (id,))
    item = cursor.fetchone()
    return render_template('edit.html', item=item)
@app.route('/update/<int:id>', methods=['POST'])
def update(id):
    name = request.form['name']
    description = request.form['description']
    
    cursor = mysql.get_db().cursor()
    cursor.execute('UPDATE items SET name=%s, description=%s WHERE id=%s', (name, description, id))
    mysql.get_db().commit()
    
    return redirect(url_for('index'))
@app.route('/delete/<int:id>')
def delete(id):
    cursor = mysql.get_db().cursor()
    cursor.execute('DELETE FROM items WHERE id=%s', (id,))
    mysql.get_db().commit()
    
    return redirect(url_for('index'))
if __name__ == '__main__':
    app.run(debug=True)
목록
templates 폴더에 index.html 파일 생성
<!DOCTYPE html>
<html>
<head>
  <title>아이템 목록</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      border: 1px solid #ddd;
      /* 약한 회색 테두리 */
    }
    th,
    td {
      border: 1px solid #ddd;
      /* 약한 회색 테두리 */
      padding: 8px;
      text-align: left;
    }
    th {
      text-align: center;
      /* 헤더 셀 가운데 정렬 */
    }
    .center {
      text-align: center;
      /* 버튼 가운데 정렬 */
    }
    h1 {
      text-align: center;
      /* 타이틀 가운데 정렬 */
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>아이템 목록</h1>
    <a href="/add" class="btn btn-success" style="float: right;">추가</a>
    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>이름</th>
          <th>설명</th>
          <th>수정</th>
          <th>삭제</th>
        </tr>
      </thead>
      <tbody>
        {% for item in items %}
        <tr>
          <td class="center">{{ item[0] }}</td>
          <td class="center">{{ item[1] }}</td>
          <td class="center">{{ item[2] }}</td>
          <td class="center"><a href="/edit/{{ item[0] }}" class="btn btn-warning">수정</a></td>
          <td class="center">
            <a href="/delete/{{ item[0] }}" class="btn btn-danger"
              onclick="return confirm('정말로 아이템을 삭제하시겠습니까?');">삭제</a>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</body>
</html>
추가
templates 폴더에 add.html 파일 생성
<!DOCTYPE html>
<html>
<head>
  <title>아이템 추가</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
    h1 {
      text-align: center;
      /* 타이틀 가운데 정렬 */
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>아이템 추가</h1>
    <form method="post" action="/add">
      <div class="form-group">
        <label for="name">이름</label>
        <input type="text" class="form-control" id="name" name="name" required>
      </div>
      <div class="form-group">
        <label for="description">설명</label>
        <textarea class="form-control" id="description" name="description" required></textarea>
      </div>
      <button type="submit" class="btn btn-primary">추가 완료</button>
    </form>
  </div>
</body>
</html>
편집
templates 폴더에 edit.html 파일 생성
<!DOCTYPE html>
<html>
<head>
  <title>아이템 수정</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h1>아이템 수정</h1>
    <form method="post" action="/update/{{ item[0] }}">
      <div class="form-group">
        <label for="name">이름</label>
        <input type="text" class="form-control" id="name" name="name" value="{{ item[1] }}">
      </div>
      <div class="form-group">
        <label for="description">설명</label>
        <textarea class="form-control" id="description" name="description">{{ item[2] }}</textarea>
      </div>
      <button type="submit" class="btn btn-primary">수정 완료</button>
    </form>
  </div>
</body>
</html>
반응형
    
    
    
  'python' 카테고리의 다른 글
| google spreadsheet api (0) | 2022.12.03 | 
|---|---|
| python 자동화 관련 google, naver 인증 문제 (0) | 2022.12.02 | 
| element 가져와서 클릭하기 (0) | 2022.11.30 | 
| selenium 설치 (0) | 2022.11.30 | 
										
									
댓글