플라스크 앱에 데이터베이스 연동
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">
<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("/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_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('/')
python의 cursor 클래스가 좀 어려웠다
https://pynative.com/python-cursor-fetchall-fetchmany-fetchone-to-read-rows-from-table/
이고잉님과의 마지막 수업 시간..! 커리큘럼이 빠르지만 좋은 것 같다
안녕하세용 혹시 대구AI스쿨 관련해서 질문드려도되나요