WEB/python

[python] 리스팅api만들기/ 제목과 내용을 써서 저장하면 바로 나타나게 하기

자바칩 프라푸치노 2021. 6. 8. 14:15

2021.06.08 - [WEB/python] - [python] 포스팅api만들기/ 제목과 내용이 db에 저장되게 하기

포스팅을 만들었으니 이제 리스팅을 만들어보자

저장하기를 누르면 바로바로 밑에 뜨게 만드는 것이다.


app.py

from flask import Flask, render_template, jsonify, request
app = Flask(__name__)


from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta_plus_week1

@app.route('/')
def home():
    return render_template('index.html')


@app.route('/diary', methods=['GET'])
def show_diary():
    diaries = list(db.diary.find({}, {'_id': False}))
    return jsonify({'all_diary': diaries})

@app.route('/diary', methods=['POST'])
def save_diary():
    title_receive = request.form['title_give']
    content_receive = request.form['content_give']
    doc ={
        'title': title_receive,
        'content': content_receive
    }
    db.diary.insert_one(doc)
    return jsonify({'msg': '저장완료!'})


if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)


index.html

 

<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
          integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
          crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
          integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
          crossorigin="anonymous"></script>

  <title>스파르타코딩클럽 | 부트스트랩 연습하기</title>
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Do+Hyeon&display=swap" rel="stylesheet">

  <style>
    *{
      font-family: 'Do Hyeon', sans-serif;
    }
    .posting-box{
      width: 500px;
      margin-top: 20px;
    }
    .wrap{
      width: 900px;
      margin: auto;
    }
    .container{
      padding-left: 50px;
    }
  </style>
  <script>
    $(document).ready(function () {
      listing()
    })

    function listing(){
      $.ajax({
        type: "GET",
        url: "/diary?sample_give=샘플데이터",
        data: {},
        success: function(response){
          let diaries = response['all_diary']
          for (let i  = 0; i< diaries.length; i++){
            let title = diaries[i]['title']
            let content = diaries[i]['content']

            let temp_html =` <div class="card">
                                  <div class="card-body">
                                    <h5 class="card-title">${title}</h5>
                                    <p class="card-text">${content}</p>
                                  </div>
                                </div>`

             $('#cards-box').append(temp_html)

                      }
        }
      })
    }
    function posting(){
        let title = $('#title').val()
        let content = $('#content').val()

        $.ajax({
          type: "POST",
          url: "/diary",
          data: { title_give:title, content_give: content },
          success: function(response){
            alert(response['msg'])
            window.location.reload()
          }
      })
    }

  </script>
</head>

<body>
<div class="wrap">
  <div class="jumbotron">
    <div class="container">
      <h1>나홀로 일기장</h1>
      <div class="posting-box">
        <div class="form-group">

          <input type="email" class="form-control" id="title" placeholder="사진 제목">
        </div>
        <div class="form-group">

          <textarea class="form-control" id="content" rows="3" placeholder="내용 입력"></textarea>
        </div>
        <button onclick="posting()" type="button" class="btn btn-primary">저장하기</button>
      </div>
    </div>
  </div>
  <div class="card-columns" id="cards-box">


  </div>
</div>

</body>

</html>

먼저 서버를 만들어주어야한다

그리고 index.html에서 listing함수를만들어준다

app.py에서 all_diary로 받았으니

이것을 변수 diaries에서 받고

for문을 돌려서 저장된 모든 값을 다 가지고 와서

card를 만들어서 append를 한다

 

728x90