<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
</head>
<body>
<script>
function search(){
const v_search = document.getElementById("search").value;
const v_keyword = document.getElementById("keyword").value;
if(v_search == "" || v_keyword== ""){
return false;
} else{
self.location.href= "{{url_for('lists')}}?search="+v_search+"&keyword="+v_keyword;
}
}
</script>
<table>
<!-- {{session["name"]}}
{{session["id"]}}
{{session["email"]}} -->
<thead>
<tr>
<td>번 호</td>
<td>제 목</td>
<td>이 름</td>
<td>내 용</td>
<td>날 짜</td>
<td>조 회 수</td>
</tr>
</thead>
<tbody>
{% for data in datas %}
<tr>
<td><a href="{{url_for('board_view',idx=data._id,search=search,keyword=keyword)}}">{{loop.index+( page-1 )*limit}}</a></td>
<td><a href="{{url_for('board_view',idx=data._id,search=search,keyword=keyword)}}">{{data.title}}</a></td>
<td><a href="{{url_for('board_view',idx=data._id,search=search,keyword=keyword)}}">{{data.name}}</a></td>
<td>{{data.contents}}</td>
<td>{{data.data_now}}</td>
<td>{{data.view}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if block_start -1 >0 %}
<a href="{{url_for('lists',page=block_start- 1 ,search=search,keyword=keyword)}}"> [이전]</a>
{% endif%}
{% for i in range( block_start, block_last +1 )%}
{% if i > last_page_num %}
{{ i }}
{% else %}
{% if i == page %}
<b>{{ i }}</b>
{% else%}
<a href="{{url_for('lists',page=i,search=search,keyword=keyword)}}">{{i}}</a>
{% endif %}
{% endif %}
{% endfor %}
{% if block_last < last_page_num %}
<a href="{{url_for('lists',page=block_last + 1 ,search=search,keyword=keyword)}}"> [다음]</a>
{% endif %}
<select name="search" id="search">
<option value="" {% if search=='' or search==-1 %} selected {% endif %}>검색대상</option>
<option value="0"{% if search== 0 %} selected {% endif %}>제목</option>
<option value="1"{% if search== 1 %} selected {% endif %}>내용</option>
<option value="2"{% if search== 2 %} selected {% endif %}>제목+내용</option>
<option value="3"{% if search== 3 %} selected {% endif %}>작성자</option>
</select>
<input type="text" name="keyword" id="keyword" {% if keyword !="" %} value={{keyword}} {% endif %}>
<input type="button" value="검색" onclick="search()">
<a href="{{url_for('board_write')}}">글작성</a>
</body>
</html>
from flask import Flask, render_template,request, jsonify,abort,redirect,url_for
from bson.objectid import ObjectId
from pymongo import MongoClient
from datetime import datetime,timezone,timedelta
import math
from flask import flash,session
client = MongoClient("mongodb+srv://sparta:test@cluster0.wu64ps9.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
db= client.num
app= Flask(__name__)
app.config["SECRET_KEY"] = "1234321"
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(seconds=5)
@app.route("/list")
def lists():
page = request.args.get("page",default=1,type=int)
limit = request.args.get("limit",4,type=int)
search = request.args.get("search",-1,type=int)
keyword = request.args.get("keyword",type=str)
query={}
search_list=[]
if search == 0:
search_list.append({"title":{"$regex":keyword}})
elif search == 1:
search_list.append({"contents":{"$regex":keyword}})
elif search == 2:
search_list.append({"title":{"$regex":keyword}})
search_list.append({"contents":{"$regex":keyword}})
elif search == 3:
search_list.append({"name":{"$regex":keyword}})
if len(search_list)>0:
query = {"$or":search_list}
print(query)
datas=list(db.write.find(query).skip((page - 1)* limit).limit(limit))
tot_count = db.write.count_documents(query)
last_page_num = math.ceil(tot_count / limit)
block_size = 3
block_num = int((page-1) / block_size)
block_start = int((block_size * block_num)+1)
block_last = math.ceil(block_start+ (block_size-1))
return render_template(
"list.html",
datas=datas,
title="리스트",
block_num=block_num,
block_last=block_last,
block_start=block_start,
limit=limit,
page=page,
last_page_num=last_page_num,
search=search,
keyword=keyword,
)
@app.route("/view/<idx>")
def board_view(idx):
# idx = request.args.get("idx")
if idx is not None:
page= request.args.get("page")
search = request.args.get("search")
keyword = request.args.get("keyword")
data = db.write.find_one({"_id":ObjectId(idx)})
if data is not None:
result={
"id":data.get("_id"),
"name":data.get("name"),
"title":data.get("title"),
"contents":data.get("contents"),
"data_now":data.get("data_now"),
"view":data.get("view"),
}
return render_template("view.html",
result=result,
title="상세보기",
page=page,
search=search,
keyword=keyword)
return abort(404)
@app.route("/write" ,methods=["GET","POST"])
def board_write():
if request.method == "POST":
name = request.form.get("name")
title = request.form.get("title")
contents = request.form.get("contents")
data_now =datetime.now().strftime("%Y-%m-%d %H:%m:%S")
doc={
"name":name,
"title":title,
"contents":contents,
"data_now":data_now,
"view":0,
}
x = db.write.insert_one(doc)
return redirect(url_for("board_view", idx=x.inserted_id))
else:
return render_template("write.html")
@app.route("/join",methods=["GET","POST"])
def member_join():
if request.method == "POST":
name = request.form.get("name",type=str)
email = request.form.get("email",type=str)
pass1 = request.form.get("pass",type=str)
pass2 = request.form.get("pass2",type=str)
print(name,email,pass1,pass2)
if name =="" or email =="" or pass1 =="" or pass2 =="":
flash("입력되지 않는 값이 있습니다.")
return render_template("joim.html")
if pass1 != pass2:
flash("비밀번호가 일치하지 않습니다.")
return render_template("join.html")
cnt=db.members.count_documents({"email":email})
print(cnt)
if cnt > 0:
flash("중복된 이메일입니다.")
return render_template("join.html")
data_now =datetime.now().strftime("%Y-%m-%d %H:%m:%S")
post={
"name":name,
"email":email,
"pass":pass1,
"joindate":data_now,
"logintime":"",
"logincount":0,
}
db.members.insert_one(post)
return "<h2>가입완료</h2>"
else:
return render_template("join.html")
@app.route("/login",methods=["GET","POST"])
def member_login():
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("pass")
data =db.members.find_one({"email":email})
# print(data)
if data is None:
flash("회원정보가 없습니다.")
return redirect(url_for("member_login"))
else:
if data.get("pass")== password:
session["email"] =email
session["name"] =data.get("name")
session["id"]=str(data.get("_id"))
session.permanent =True
return redirect(url_for("lists"))
else:
flash("비밀번호가 일지하지않습니다.")
return redirect(url_for("member_login"))
return ""
else:
return render_template("login.html")
if __name__=="__main__":
app.run(debug=True,port=5001)