[DAY9]데이터베이스 Python_연동

MINJOO·2022년 3월 31일
0

2022 DaeguAI school

목록 보기
7/8

학습내용 (Glitch 활용)

  1. topics의 배열을 만들때 각 값은 id, title, body 값을 가진다.


2. 함수 밖에 nextId가 설정되어있음
3. 위쪽에 global(밖) nextId를 기입해주기! (아래 그림 참고)

  1. 지금실행되는 페이지로 가기위해 nextId로 돌아가기 위해서 -1을 해준다.

  2. 최종 코드

> from flask import Flask, request, redirect


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):
  liTags = ''
  for topic in topics:
    liTags = liTags + f'<li><a href="/read/{topic["id"]}/">{topic["title"]}</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):
>   title = ''
>   body = ''  
>   for topic in topics :
>     if topic['id'] == id:
>       title = topic['title']
>       body = topic['body']
>       break;
>   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()

어려운 점

코드 작성 중 사소한 오탈자 조심!!!

학습소감

sql이라는 관계형 데이터베이스에 관하여도 배웠으나 새로운 정보가 생길때 마다 각 정보마다 어떻게 연관해서 활용해야하는지 감이 안잡힌다.

profile
코딩 신생아

0개의 댓글