[Flask] Client data를 Server DB에 저장하기

Yewon Kim·2020년 6월 23일
0

Flask

목록 보기
2/3

프로젝트 폴더에 common.js 파일 추가

📁static
└📄common.js
📁templates
└📄index.html
📄app.py

이제부터 common.js는 templates 폴더 내의 여러 html 파일에서 공통적으로 사용될 함수들을 모아두는 JavaScript 파일이 될 것입니다.

head tag에 ajax와 common.js를 호출하는 script 작성

📄index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/common.js"></script>

client로부터 data input을 받는 html 작성

📄index.html

<body>
  <div id="postingBox">
    <select name='categories' id="categoryCode">
      <option value='1'>Category 1</option>
      <option value='2'>Category 2</option>
      <option value='3'>Category 3</option>
    </select>
    <textarea id="postingBody"></textarea>
    <button onclick="post_article()">Post</button>
  <div>
</body>

client data를 server의 api로 넘겨주는 ajax 함수 작성

📄common.js

function post_article() {
  let post_body = $('#postingBody').val();
  let category_code = $('#categoryCode').val();

  $.ajax({
    type: "POST",
    url: "/api/postarticle",
    data: {
      'category_code_give': category_code,
      'post_body_give': post_body
    },
    success: function (response) {
      if (response['result'] == 'success') {
        window.location.reload()
      }
    }
  })
}

api를 통해 받은 client data를 server의 DB에 저장

📄app.py

@app.route('/api/postarticle', methods=['POST'])
def post_article():
    category_code_receive = request.form['category_code_give']
    post_body_receive = request.form['post_body_give']
    
    article = {
            'category_code': category_code_receive,
            'post_body': post_body_receive
    }
    
    db.articles.insert_one(article)
    return jsonify({'result': 'success'})

다음은 Server DB에 저장한 data를 client로 불러오는 작업을 해보겠습니다.

profile
산업의 안팎에서 투자의 원칙을 배우고 싶은 학생입니다.

0개의 댓글