from flask import Flask, render_template, request, redirect, url_for, jsonify, abort
from bson.objectid import ObjectId
from datetime import datetime
from pymongo import MongoClient
client = MongoClient(
""
)
db = client.jinja
app = Flask(__name__)
@app.route("/", methods=["GET"])
def home():
topics = list(db.egoing.find({}))
return render_template("index.html", topics=topics)
@app.route("/create/", methods=["GET", "POST"])
def create():
if request.method == "GET":
return render_template("create.html")
elif request.method == "POST":
global nextID
title = request.form["title"]
body = request.form["body"]
doc = {
"title": title,
"body": body,
}
# url = "/read/" + str(nextID) + "/"
x = db.egoing.insert_one(doc)
return redirect(url_for("read", idx=x.inserted_id))
@app.route("/read/<idx>")
def read(idx):
# idx = request.args.get("idx")
if idx is not None:
data = db.egoing.find_one({"_id": ObjectId(idx)})
if data is not None:
result = {
"id": data.get("_id"),
"title": data.get("title"),
"body": data.get("body"),
}
return render_template("read.html", result=result)
return abort(400)
@app.route("/update/<idx>/", methods=["GET","POST"])
def update(idx):
if request.method == "GET":
if id is not None:
data = db.egoing.find_one({"_id": ObjectId(idx)})
if data is not None:
result = {
"id": data.get("_id"),
"title": data.get("title"),
"body": data.get("body"),
}
return render_template("update.html", result=result)
elif request.method == "POST":
# 스파르타 보고 다시공부~~~여기까지
title = request.form["title"]
body = request.form["body"]
for topic in topics:
if id == topic["id"]:
topic["title"] = title
topic["body"] = body
break
url = "/read/" + str(id) + "/"
return redirect(url)
@app.route("/delete/<int:id>/", methods=["POST"])
def delete(id):
for topic in topics:
if id == topic["id"]:
topics.remove(topic)
break
return redirect("/")
if __name__ == "__main__":
app.run(debug=True, port=5000)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>수정하기</title>
<style>
p{
background-color: burlywood;
width: 300px;
align-items: center;
}
</style>
</head>
<body>
<h1> 수정하기 </h1>
<table>
<tbody>
<form action="/update/{{id}}/" method="POST">
<p name="_id">{{result.id}}</p>
<p><input type="text" name="title" placeholder="title" value="{{result.title}}"></p>
<p><textarea name="body" placeholder="body">{{result.body}}</textarea></p>
<p><input type="submit" value="update"></p>
</form>
</tbody>
</table>
<a href="/"><button>홈</button></a>
</body>
</html>