<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>리스트</title>
</head>
<body>
{% if datas|length > 0 %}
<table>
<thead>
<tr>
<td>번 호</td>
<td>아이디</td>
<td>이 름</td>
<td>이메일</td>
<td>출생연도</td>
</tr>
</thead>
<tbody>
<!-- 반복되는 구간간 -->
{% for item in datas%}
<tr>
<td>{{item.number}}</td>
<td>{{item.user_id}}</td>
<td>{{item.userName}}</td>
<td>{{item.email}}</td>
<td>{{item.birthYear}}</td>
</tr>
{% endfor %}
<!-- 반복되는 구간끝 -->
</tbody>
</table>
{% else %}
<h2>데이터가 없습니다.</h2>
{% endif %}
</body>
</html>
import pymysql
from flask import Flask,request,render_template,abort,url_for,redirect
app=Flask(__name__)
conn =pymysql.connect(
host="127.0.0.1",
user="root",
passwd="cb02077075",
db='mylist',
charset = "utf8",
autocommit = True
)
cur= conn.cursor()
@app.route("/list")
def lists():
cur.execute("SELECT * FROM userTable")
rows = cur.fetchall()
columns = [desc[0] for desc in cur.description]
datas = [dict(zip(columns, row)) for row in rows]
return render_template("list.html",datas=datas)
@app.route("/write",methods=["GET","POST"])
def board_write():
if request.method == "POST":
user_id = request.form.get("user_id")
userName = request.form.get("userName")
email = request.form.get("email")
birthYear= request.form.get("birthYear")
sql = ("INSERT INTO userTable(user_id,userName, email,birthYear) VALUES(%s,%s,%s,%s)")
cur.execute(sql,(
user_id,
userName,
email,
birthYear
))
x=cur.lastrowid #키값받기
return redirect(url_for("board_view",idx=x))
else:
return render_template("write.html")
@app.route("/view/<idx>")
def board_view(idx):
# idx=request.args.get("idx")
if idx is not None:
try:
idx = int(idx)
cur.execute("SELECT * FROM userTable WHERE number=%s",(idx,)) #콤마필수
row = cur.fetchone()
# print(row)
if row is not None:
result={
"number":row[0],
"user_id":row[1],
"userName":row[2],
"email":row[3],
"birthYear":row[4]}
# print(f'번호:{nu} 아이디:{data2} 이름:{data3} 이메일:{data4} 출생연도:{data5}')
return render_template("view.html",result=result)
except ValueError:
return "잘못된 번호 형식입니다."
return "해당내용이 없습니다."
if __name__ == "__main__":
app.run(debug=True,port=9000)