상세 컨텐츠

본문 제목

mongo db 추가 ~~~ 읽기 까지 완성

카테고리 없음

by bumychoi 2024. 1. 13. 23:26

본문

from flask import Flask, render_template, request, redirect, url_for, jsonify, abort
from bson.objectid import ObjectId

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 id is not None:
        data = db.egoing.find_one({"_id":ObjectId(idx)})
        print(data)
        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/<int:id>/", methods=["GET", "POST"])
def update(id):
    if request.method == "GET":
        title = ""
        body = ""
        for topic in topics:
            if id == topic["id"]:
                title = topic["title"]
                body = topic["body"]
                break

        return render_template("update.html", id=id, title=title, body=body)
    elif request.method == "POST":
        global nextID
        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>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <style>
        table{
            width: 400px;
        }
    </style>

</head>

<body>
    <h1><a href="/">WEB</a></h1>
    <table>
        <thead>
            <tr>
                <td>번 호</td>
                <td>제 목</td>
                <td>내 용</td>
            </tr>
            <hr>
        </thead>
        <tbody>
            {% for topic in topics %}
            <tr>
                <td>
                    <a href="{{url_for('read', idx=topic._id)}}">
                        {{loop.index}}
                    </a>
                </td>    
                <td>
                    <a href="{{url_for('read', idx=topic._id)}}">
                        {{topic.title}}
                    </a>
                </td>
                <td>
                    {{topic.body}}
                </td>
            </tr>
            {% endfor %}
        </tbody>
       
    </table>
    <hr>
    <h2>환영합니다.</h2>
        HELLO, WEB
    <br>
    <a href="/create/"><button>등록하기</button></a>
</body>

</html>