2022/04/01

jungkwanlee·2022년 4월 1일
0

코딩일지

목록 보기
8/108

1) 학습한 내용

어제 배웠던 데이터베이스를 이어서 듣게 되었다. 수업은 glitch.com을 통해서 배우는데 여기서 나는 강의 내용대로 sqlite3를 작동시켰다. 그리고 다음과 같은 코드를 작성했다.
$ sqlite3

그러면 sqlite가 열리는데 여기에 데이터베이스를 작성했다.

sqlite> .open db.sqlite3
sqlite> CREATE TABLE topics(
   ...> id INTEGER PRIMARY KEY,
   ...> title TEXT NOT NULL,
   ...> body TEXT
   ...> )
   ...> ;
sqlite> .tables
topics
sqlite> .schema topics
CREATE TABLE topics(
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
body TEXT
);

그리고 새로운 걸 추가할 때는 다음과 같은 코드를 작성했다.

sqlite> INSERT INTO topics (title,body) VALUES('SQLite','SQLite is ...');

여기서, 작성했던 sqlite의 내용을 확인한다면 아래의 코드를 작성한다.

sqlite> SELECT * FROM topics;

그러면 아래의 코드가 출력된다.

1|SQLite|SQLite is ...

sqlite를 나갈때는 아래의 코드를 작성한다.

sqlite> .exit

만약에 데이터베이스를 작성중에 오타가 날 경우, 아래의 코드를 작성해서 지우면 된다.

DROP TABLE topics:

그리고, glitch.com에서 새로운 파일인 create.py를 만들고 다음과 같은 코드를 집어넣었더.

import sqlite3
conn = sqlite3.connect('db.sqlite3')
curor = conn.cursor()
title = input('title? ')
body = input('body? ')
curor.execute('INSERT INTO topics (title,body) VALUES(?,?)',(title,body))
conn.commit()
conn.close()

import read

그리고, 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()

전체적인 server.py에 수정된 소스코드는 다음과 같다.

from flask import Flask, request, redirect
import sqlite3

app = Flask(__name__)

topics = [
  {"id":1, "title":"html", "body":"html is ...."},
  {"id":2, "title":"css", "body":"css is ...."},
  {"id":3, "title":"js", "body":"js is ...."}
]
nextId = 4

def template(content, id=None):
  conn = sqlite3.connect('db.sqlite3')
  cs = conn.cursor()
  cs.execute('SELECT * FROM topics')
  topics = cs.fetchall()
  conn.close()
  liTags = ''
  for topic in topics:
    liTags = liTags + f'<li><a href="/read/{topic[0]}/">{topic[1]}</a></li>'
  return f'''
  <html>
    <body>
      <h1><a href="/">WEB</a></h1>
      <ol>
        {liTags}
      </ol>
      {content}
      <ul>
        <li><a href="/create/">create</a></li>
        <li>
          <form action="/delete/{id}/" method="POST">
            <input type="submit" value="delete">
          </form>
        </li>
      </ul>
    </body>
  </html>
  '''

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

@app.route("/read/<int:id>/")
def read(id):
  conn = sqlite3.connect('db.sqlite3')
  cs = conn.cursor()
  cs.execute('SELECT * FROM topics WHERE id=?', (id,))
  topic = cs.fetchone()
  conn.close()
  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():
  global nextId
  title = request.form['title']
  body = request.form['body']
  newTopic = {"id":nextId, "title": title, "body": body}
  topics.append(newTopic)
  nextId = nextId + 1
  return redirect(f'/read/{nextId-1}/')


@app.route('/delete/<int:id>/', methods=['POST'])
def delete(id):
  for topic in topics:
    if topic['id'] == id:
      topics.remove(topic)
      break;
  return redirect('/')

# @app.route('/update/')
# def update():
#   return 'Update'


app.run()

위의 코드는 Flask를 데이터베이스 방식으로 동작시키는 코드이다. 그 다음은 삭제 기능을 구현 시켰는데, 남은 시간은 강사의 지시로 부츠스트랩을 통해 백엔드의 화면을 꾸민 것이다.

from flask import Flask, request, redirect
import sqlite3

app = Flask(__name__)

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">'
  conn = sqlite3.connect('db.sqlite3')
  cs = conn.cursor()
  cs.execute('SELECT * FROM topics')
  topics = cs.fetchall()
  conn.close()
  liTags = ''
  for topic in topics:
    liTags = liTags + f'<li><a href="/read/{topic[0]}/">{topic[1]}</a></li>'
  return f'''
  <html>
    <head>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
      <style>
        h1{{
          border-bottom:10px solid green;
        }}
      </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):
  conn = sqlite3.connect('db.sqlite3')
  cs = conn.cursor()
  cs.execute('SELECT * FROM topics WHERE id=?', (id,))
  topic = cs.fetchone()
  conn.close()
  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']
  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.route('/update/')
# # def update():
# #   return 'Update'
 

app.run()

2) 학습내용 중 어려웠던 점

학습은 전체적으로 지시한대로 움직여서 무난하게 진행되었다. 그저, 오타에 주의한다면 강사의 지시대로 무난하게 진행되었다.

3) 해결방법

어제와 동일했었다. 백엔드와 데이터베이스를 배우려면 결국 스스로 공부해야 한다.

4) 학습소감

오늘은 백엔드와 데이터베이스에 관한 수업이 끝났다. 다음 주에는 본격적으로 AI에 관한 수업에 들어갈 것이다. 예습과 복습은 반드시 해야 할 것이다. 어려운 것도 처음이 어렵지 그 다음부터는 점차적으로 늘어나는 것이다. 그게 기술이다.

0개의 댓글

관련 채용 정보