[0401]개발일지

김규리·2022년 4월 1일
0

학습한내용

Python과 데이터베이스 연동

Python으로 Database 핸들링
import sqlite3
con = sqlite3.connect('database')
cur = con.cursor()

cur.execute('SELECT * FROM topics')
topics = cur.fetchall()
print(topics)

Flask에서 Sqlite 사용
def template(content, id=None):
conn = sqlite3.connect("test.db", isolation_level=None)
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>'
    
   
   

Delete 함수 작성
@app.route('/delete/<int:num>/')
def delete(num):
conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()
cursor.execute('DELETE FROM topics WHERE id=?', (num,))
conn.commit()
conn.close()
return template(f'

Delete Succeeded

Content number {num} deleted.')

<학습코드>

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 = ''
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'

  • {topic[1]}
  • '
    return f'''

    WEB

      {liTags}
    {content}
    create {contextUI}
    @app.route("/") def index(): return template('

    Welcome

    Hello, WEB!') @app.route("/read//") 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'

    {title}

    {body}', id) @app.route('/create/') def create(): content = '''

    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//', 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('/') ## 학습내용 중 어려웠던 점 데이터베이스 연동할 때 삐걱거리는 부분이 많았음 ## 해결방법

    복습과 함수 제대로 파악하기

    학습소감

    html, css, javascript, python을 짧은시간동안 전체적으로 학습하게 되었는데 중요한 내용을 배울 수 있어 알찼다. 매일 주기적으로 복습해야할 것 같다.

    profile
    코딩

    0개의 댓글