사전강의 5주차 정리

lovjgb·2022년 7월 15일

강의요약

목록 보기
4/5

1. 준비하기

  1. 폴더 만들기

  2. 프로젝트 새로 시작 (venv폴더가 만들어 지는지 확인)

  3. Flask 서버 프레임워크 사용 시 필요한 기본 폴더구조를 세팅한다.

    static, templates> index.html, app.py 세팅

    static : 이미지, css파일을 넣어두는 역할

    templates : HTML파일을 담아두고, 불러오는 역할

  4. 패키지 설치 : flask, pymongo, dnspython(feat. Python 인터프리터에서)

  5. Python 파일 : flask 프레임워크를 사용하여 쉽게 서버를 만들어준다.

    1. 내 컴퓨터에서 서버를 돌리고 직접 크롬으로 접속 = “로컬 개발환경”
    2. localhost:5000 이라는 사이트에서 작업한다.
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
##flask의 내장함수 

from pymongo import MongoClient
client = MongoClient('몽고db')
db = client.dbsparta

@app.route('/')
def home():
   return render_template('index.html')
## retuen 뒤에 서버에 연결 시 띄워줄 내용을 적는 것입니다.
## render_template 라는 내장함수를 통해서 index.html을 연결하여 해당 html을 화면에 띄워줄 수 있게 됩니다.
## URL 별로 함수명이 같거나, route('/') 등의 주소가 같으면 안됩니다.

if __name__ == '__main__':  
   app.run('0.0.0.0',port=5000,debug=True)
  1. 서버 연결 유무 확인하기

2. 기획하기

  • 어떤 데이터를 GET,POST할지 생각해보자
    1. (POST)버킷리스트 입력
      • 입력 데이터 → DB
      1. 입력값(POST할 데이터값)
        1. done을 할 경우 해당 값의 번호가 있어야 해당 번호를 인식하게 해주기 위해서.
      2. 번호 매기기 ( 1씩 늘어나도록)
      3. 완료 유무 ( 0 or 1 )
    2. (GET)버킷리스트 사이트 로딩
      • 조회시 DB → 서버 →클라이언트
      1. DB값 조회(뿌려주기)
    3. (POST)버킷리스트 완료 시 데이터 처리
      • 완료 시 데이터 → DB바꾸기
      1. 데이터를 바꿔주기

3. (POST)버킷리스트 입력

  1. index.html : a.jax를 통해 클라→(1) html →(2)서버로 보낸다.
function save_bucket() {
					// (1) 입력창에 입력한 값을 가지고와줘!
          const bucketlist = $('#bucket').val()
					
					// (2) bucket_give라는 데이터이름으로 bucketlist값을
					//     서버로 보내줘!
          $.ajax({
              type: "POST",
              url: "/bucket",
              data: {bucket_give: bucketlist},
              success: function (response) {
                  alert(response["msg"])
									//app.py의 return값을 alert해줘!
                  window.location.reload()
              }
          });
      }
  1. app.py : 받은 (1)입력값에 (2)번호를 매기고 (3)완료유무를 넣어준다. 그 (1,2,3)값을 DB로 보내준다.(4)
    1. 이때!! app.py에서 번호를 매기는 함수와 완료유무 함수를 넣는 작업을 해줘야된다.
@app.route("/bucket", methods=["POST"])
def bucket_post():

	# (1) 입력값 가지고오기.
  bucket_receive = request.form['bucket_give']
	
  # (2) 번호 매기기 
	bucket_list = list(db.bucket.find({}, {'_id': False}))
	# DB를 모두 조회한다.
  bucket_number = len(bucket_list) +1
	# DB의 순서를 세주고 +1값을 매겨준다.
	
	# (4)DB로 위의 3개의 값을 명명해준 후 전송.!
  doc = {
    'bucket':bucket_receive
    'num': bucket_number
    'done': 0
  }
  db.bucket.insert_one(doc)
  return jsonify({'msg': '버킷리스트 등록완료!'}) #alert될 값

4. (GET)버킷리스트 사이트 로딩 시 조회

  1. index.html : (1)서버→html로 data를 달라고 요청한다.
<script>
    $(document).ready(function () {
        show_bucket();
    });

    function show_bucket() {
        $.ajax({
            type: "GET",
            url: "/bucket",
            data: {},
            success: function (response) {
										alert(response["msg"]
						}
			});
	}
  1. app.py: DB→서버로 데이터를 가지고 온다. →html에 보내준다.
@app.route("/bucket", methods=["GET"])
def bucket_get():
		all_bucket = list(db.bucket.find({},{'_id':False}))
		# db의 bucket 콜랙션 안에 들어있는 모든 데이터를 뽑아줘
		# 그리고 그 데이터를 all_bucket이라고 선언할게
    return jsonify({'buckets':all_bucket})
		# 그 담은 데이터(all_bucket)를 buckets라는 이름으로 html한테 보내줘~
		# * 무조건 key:value 형태로 보내줘야 됩니다.(제이슨 형태로)
  1. index.html : 클라이언트(브라우저)에 뿌려줄 코드를 짠다.
$(document).ready(function () {
      show_bucket();
  });
//새로고침 할때 아래를 실행시켜줘!

  function show_bucket() {
      $.ajax({
          type: "GET",
          url: "/bucket",
          data: {},
          success: function (response){
										//* 여기서 바로 []로 가져올수 없다.
              const bucket_list = response['buckets'] 
							//가져온 데이터에서 'buckets값을 가지고온다.
              for (let i =0; i< bucket_list.length; i++) { 
									// 그 가져온 데이터를 0부터~돌려!
                  let num = bucket_list[i]['num'] 
									// 데이터의 num값을 선언!
                  let bucket = bucket_list[i]['bucket']
                  let done = bucket_list[i]['done']

                  let temp_html = `` 
									// if문 실행 전에 ``템플릿 리터럴을 선언해준다.
                  if (done == 0) { 
                      temp_html = `<li>
                                    <h2>✅ ${bucket}</h2>
                                    <buttontoken interpolation">${num})" type="button" class="btn btn-outline-primary">완료!</button>
                                     </li>`
                  } else {
                      temp_html = `<li>
                                      <h2 class="done">✅ ${bucket}</h2>
                                      </li>`
                  }
                  $('#bucket-list').append(temp_html) 
									// bucket-list라는 id 태그에 넣어줘!
              }

          }
      });
  }

// ``을 선언할 때 const로 선언하면 작동이 안된다.
// 가져온 데이터에서 바로 경로지정[]을 하면 안되고 선언해서 경로를 지정하자
// append는 if문을 나간 후에 실행한다.

5. (POST) 완료 클릭 시 DB값 변화주기

  1. index.html : 클릭했던 버킷리스트의 num값을 POST요청으로 서버에 보내준다.
function done_bucket(num) { 
          $.ajax({
              type: "POST",
              url: "/bucket/done",
              data: {'done_give': num}, 
							//done_give라는 이름으로 num값을 서버에 보내줘!
              success: function (response) {
                  alert(response["msg"]) 
									// msg값을 알럿해줘!
                  window.location.reload() 
									// 새로고침 해줘!
              }
          });
      }
  1. app.py : 받은 num값과 일치하는 데이터의 done값을 1로 바꿔준다.
@app.route("/bucket/done", methods=["POST"])
def bucket_done():
  num = request.form['done_give'] 
# html에서 보내준 done_give값을 num이라고 할게
  db.bucket.update_one({'num': int(num)}, {'$set': {'done': 1}}) 
# done값 ->1로 바꿔줘! / num값을 문자열로 받아줘! int처리!
  return jsonify({'msg': '버킷 완료!'}) 
profile
lovjgb

0개의 댓글