[S GALLERY] 데이04

sooj·2021년 7월 5일
0

POST 와 GET

파이썬 파일에서 POST 와 GET 의 method 를 통해 데이터를 받아 저장하거나, 저장해놓은 데이터를 받아올 수 있다.

이제 내가 만든 "SGpost.html" 에서 입력하는 제목, 내용, 주소, 이미지 파일 등 이 데이터를 받아서 저장하는 역할, POST 를 만들어보기로 한다.

@app.route('/gall', methods=['POST'])
def savepic():

db.sgalls.insert_one(doc)
return jsonify(result='success')

method를 POST로 , savepic 이라는 함수를 만들었다.

이 전에 만들어 놓은 html 파일에서 보면 각 항목 별로 id를 주었다.
다시 갖고 와서 본다.

<form>
            <div class="container">
                <div class="row">
                    <div class="col-25">
                        <label for="title">제목</label>
                    </div>
                    <div class="col-75">
                        <input type="text" id="title" name="title" placeholder="20자 이내">
                    </div>
                </div>
                <div class="row">
                    <div class="col-25">
                        <label for="ncity">나라/도시</label>
                    </div>
                    <div class="col-75">
                        <select id="ncity" name="ncity">
                            <option value="Newyork">Newyork</option>
                            <option value="LosAngeles">Los Angeles</option>
                            <option value="Seattle">Seattle</option>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-25">
                        <label for="story">스토리</label>
                    </div>
                    <div class="col-75">
                        <textarea id="story" name="story" placeholder="100자 이내" style="height:200px"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-25">
                        <label for="addrs">주소</label>
                    </div>
                    <div class="col-75">
                        <input type="text" id="address" name="address">
                    </div>
                </div>

                

제목은 title, 나라/도시는 ncity, 스토리는 story, 주소는 address 로 id를 설정해주었다.

설정해준 id 를 이용해서 DB를 받아 저장하고 불러올 예정이다.

title_receive = request.form['title_give']
ncity_receive = request.form['ncity_give']
story_receive = request.form['story_give']
address_receive = request.form['address_give']

doc = {
       'title': title_receive,
       'ncity': ncity_receive,
       'story': story_receive,
       'address': address_receive
   }

이미지도 파일 업로드 하여 저장할 예정이지만, 이 때는 다른 코드가 필요하므로 일단 텍스트를 DB에 먼저 저장시킨다.

클라이언트에서 주기.

서버 쪽에서 받기를 했으면 클라이언트에서 주기를 해야 할 차례이다.

<script type="text/javascript">

        function savepic() {
            
            let title = $("#title").val();
            let ncity = $("#ncity").val();
            let story = $("#story").val();
            let address = $("#address").val();

            let form_data = new FormData()

            form_data.append("title_give", title) 
            form_data.append("ncity_give", ncity)
            form_data.append("story_give", story)
            form_data.append("address_give", address)


            $.ajax({
                type: "POST",
                url: "/gall",
                enctype:"multipart/form-data",
                cache:false,
                processData:false,
                contentType:false,
                data:form_data,
                success: function (response) {
                    console.log(response)
                    if (response["result"] == "success") {
                        alert("저장이 완료되었습니다.");
                        location.href = `저장이 완료되면 이동할 페이지`
                    } else {
                        alert("저장이 완료되지 않았습니다.");
                    }
                }
            })
        }

나는 title, ncity, story, address 부분에 입력을 받을 거기에 변수로 줘야한다. 입력 받는 거에 따라 다르기 때문이다.

좀 더 자세히 보자.

$.ajax({
                type: "POST",
                url: "/gall",
       })

ajax 부분을 보면 type 은 POST
변수 savepic에 서버주소를 "/gall" 로 설정했기에 url에 "/gall" 로 적어준다.

success: function (response) {
                    console.log(response)
                    if (response["result"] == "success") {
                        alert("저장이 완료되었습니다.");
                        location.href = `/view/${response["city"]}`
                    } else {
                        alert("저장이 완료되지 않았습니다.");
                    }
                }

function (response) 로 받는데 result 값이 success 면
alert, "저장이 완료되었습니다." 라고 알람창이 뜬다.

profile
개발일지 모음집

0개의 댓글