20220401 flask-DB연결

학습한 내용

WEB에 DATABASE 연결하기

read.py 만들기

import sqlite3
conn = sqlite3.connect('db.sqlite3')
curor = conn.cursor()
curor.execute('SELECT * FROM topics')
topics = curor.fetchall()
for topic in topics:
  print(topic[0], topic[1])
conn.close()

create.py 만들기

import sqlite3
conn = sqlite3.connect('db.sqlite3')

## cursor 만들기
curor = conn.cursor()

##값 입력받기
title = input('title? ')
body = input('body? ')

## 입력받은 값 'db.sqlite3'에 INSERT
curor.execute('INSERT INTO topics (title, body) VALUES(?, ?)', (title, body))
conn.commit()
conn.close()

import read

WEB에 read.py, create.py connect 하기

from flask import Flask, request, redirect
import sqlite3

app = Flask(__name__)

## 현재 정의해 놓은 topics 변수를 'db.sqlite3'의 topics로 대체할 예정
topics = [
  {"id":1, "title":"html", "body":"html is ...."},
  {"id":2, "title":"css", "body":"css is ...."},
  {"id":3, "title":"js", "body":"js is ...."}
]

def template(content, id=None):
    contextUI = ''
    if id != None:
      	contextUI = '<input type="submit" value="delete" class="btn btn-dark">'
	## 1. 'db.sqlite3'와 연결
    conn = sqlite3.connect('db.sqlite3')
    cs = conn.cursor()
    cs.execute('SELECT * FROM topics')
    topics = cs.fetchall()
    ## connect 닫아주기
    conn.close()
    liTags = ''
    for topic in topics:
    	## '/read/' page 숫자를 'db.sqlite3'의 topics의 id로 설정하고 내용을 topics의 title로 설정
      	liTags = liTags + f'<li><a href="/read/{topic[0]}/">{topic[1]}</a></li>'
    return f'''
    <html>
      	<head>
        	<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        	<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
        	<style>
              h1{{
                border-bottom:10px solid green;
              }}
              h1>a{{
                text-decoration:none;
              }}
          </style>
      	</head>
      	<body class="container">
        	<input type="button" value="night" onclick="
              document.querySelector('body').style.backgroundColor = 'black';
              document.querySelector('body').style.color = 'white';
            ">
        	<h1><a href="/">WEB</a></h1>
        	<ol>
          		{liTags}
        	</ol>
        	{content}
        	<form action="/delete/{id}/" method="POST">
          		<div class="btn-group" role="group" aria-label="Basic example">  
            		<a href="/create/" class="btn btn-dark">create</a>
            		{contextUI}
          		</div>
        	</form>  
      	</body>
    </html>
    '''

@app.route("/")
def index():
  	return template('<h2>Welcome</h2>Hello, WEB!')

@app.route("/read/<int:id>/")
def read(id):	## id parameter 입력
	## 1. 'db.sqlite3'와 연결
    conn = sqlite3.connect('db.sqlite3')
    cs = conn.cursor()
    cs.execute('SELECT * FROM topics WHERE id=?', (id,))
    topic = cs.fetchone()	## 하나씩만 fetch하기
    conn.close()
    ## read page에 따라 표시되는 내용
    title = topic[1]
    body = topic[2]
    return template(f'<h2>{title}</h2>{body}', id)

@app.route('/create/')
def create():
    content = '''
        <form action="/create_process/" method="POST">
            <p><input type="text" name="title" placeholder="title"></p>
            <p><textarea name="body" placeholder="body"></textarea></p>
            <p><input type="submit" value="create"></p>
        </form>
      '''
    return template(content)

@app.route('/create_process/', methods=['POST'])
def create_process():
    title = request.form['title']
    body = request.form['body']
    ## 2. 'db.sqlite3'와 연결
    conn = sqlite3.connect('db.sqlite3')
    cs = conn.cursor()
    cs.execute('INSERT INTO topics (title, body) VALUES(?,?)',(title,body))
    id = cs.lastrowid
    conn.commit()
    conn.close()
    return redirect(f'/read/{id}/')


@app.route('/delete/<int:id>/', methods=['POST'])
def delete(id):
 
    conn = sqlite3.connect('db.sqlite3')
    cs = conn.cursor()
    cs.execute('DELETE FROM topics WHERE id = ?',(id,))
    conn.commit()
    conn.close()
 
  	return redirect('/')

app.run()
  • 실행 결과

학습내용 중 어려웠던 점

DB를 연결하려다 보니 코드가 조금 복잡해져서 헷갈렸다.

해결방법

오늘 만든 코드 반복해서 복습하기

학습소감

지금까지 배웠던 내용을 다 적용해 볼 수 있어서 좋았다.

참고
https://getbootstrap.com/docs/5.1/components/button-group/

좋은 웹페이지 즐겨찾기