왕초보 코딩 공부 일지 _ 4주차

yeongah choi·2021년 9월 4일
0

코딩 공부

목록 보기
4/10

4주차는 크롤링 배움
진짜 한번해서는 될 일이 아닌 것 같음
따라하기에 급급했다.

1.일단 폴더셋팅부터

  • static 폴더 생성
  • templates 폴더 생성 -> html파일 생성
  • app.py 파일 생성
  1. flask 내장함수 render_template 복붙 ->app.py 파일
from flask import Flask, render_template
app = Flask(__name__)

## URL 별로 함수명이 같거나,
## route('/') 등의 주소가 같으면 안됩니다.

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

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

get /post 기본 양식

코드를@app.route('/review', methods=['POST'])
def write_review():
    # title_receive로 클라이언트가 준 title 가져오기
    title_receive = request.form['title_give']
    # author_receive로 클라이언트가 준 author 가져오기
    author_receive = request.form['author_give']
    # review_receive로 클라이언트가 준 review 가져오기
    review_receive = request.form['review_give']

    # DB에 삽입할 review 만들기
    doc = {
        'title': title_receive,
        'author': author_receive,
        'review': review_receive
    }
    # reviews에 review 저장하기
    db.bookreview.insert_one(doc)
    # 성공 여부 & 성공 메시지 반환
    return jsonify({'msg': '리뷰가 성공적으로 작성되었습니다.'}) 입력하세요

과제 제출
app.py

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.dbhomework


## HTML 화면 보여주기
@app.route('/')
def homework():
    return render_template('index.html')


# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
    name_receive = request.form['name_give']
    people_receive = request.form['people_give']
    date_receive = request.form['date_give']
    email_receive = request.form['email_give']

    doc = {
        'name': name_receive,
        'people': people_receive,
        'date': date_receive,
        'email': email_receive
    }

    db.deutschreise.insert_one(doc)

    return jsonify({'msg': 'Bist du bereit?'})



@app.route('/order', methods=['GET'])


def view_orders():
    orders = list(db.deutschreise.find({}, {'_id': False}))

    return jsonify({'all_orders': orders})



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


index.html

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

<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>4주차 과제</title>

<meta property="og:title" content="nach Deutschland" />
<meta property="og:description" content="독일 갈 사람 어서 와!" />
<meta property="og:image" content="{{ url_for('static', filename='ogimage-800x400.jpg') }}" />



   <link rel="preconnect" href="https://fonts.googleapis.com">
   <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
   <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300&display=swap" rel="stylesheet">

   <style>
       * {
           font-family: 'Noto Sans KR', sans-serif;
       }

       .title_image {
           width: 600px;
           height: 500px;
           border-radius: 10px;
           margin-top: 50px;
           background-image: url('https://post-phinf.pstatic.net/MjAxODA2MDRfMjMy/MDAxNTI4MDcxNDMzMTQy.kdsUMGdPiGzoASAFfeCZjoRwDcR2xS3gD3TU-UkL4u4g.DKGmumvOvyGBxP3l9geW7AXGfE92o1ZRQsh2qvPmOV4g.JPEG/%EB%8F%85%EC%9D%BC_%EC%97%B0%EB%B0%A9%EC%9D%98%ED%9A%8C_%EC%9D%98%EC%82%AC%EB%8B%B9.jpg?type=w1200');
           background-position: center;
           background-size: cover;
       }

       .wrap {
           margin: auto;
           width: 600px;
       }

       .btn {
           margin: 300px;
           margin: auto;
           display: block;
           background-color: gold;
           color: whitesmoke;
       }

       .price {
           font-size: 20px;
           color: cornflowerblue;
           font-weight: bold;

       }

       .form-group {
           margin-top: 20px;

       }

       .btn_rate {
           border-color: aqua;
           border-width: 0px;
           background-color: cornflowerblue;
           color: white;
       }
   </style>

   <script>
       $(document).ready(function () {
           q1();
           order_listing();
       });

       function q1() {
           $.ajax({
               type: "GET",
               url: "http://spartacodingclub.shop/sparta_api/rate",
               data: {},
               success: function (response) {
                   let rate = response['rate']
                   $("#rate").text(rate);
               }
           })
       }


       function order() {
           let name = $('#exampleFormControlInput1').val()
           let people = $('#exampleFormControlSelect1').val()
           let date = $('#exampleFormControlInput2').val()
           let email = $('#exampleFormControlInput3').val()


           $.ajax({
               type: "POST",
               url: "/order",
               data: {name_give: name, people_give: people, date_give: date, email_give: email},
               success: function (response) {
                   alert(response["msg"]);
                   window.location.reload();
               }
           })
       }

       function order_listing() {
           $.ajax({
               type: "GET",
               url: "/order",
               data: {},
               success: function (response) {
                   let order_1 = response['all_orders']
                   for (let i = 0; i < order_1.length; i++) {
                       let name = order_1[i]['name']
                       let people = order_1[i]['people']
                       let date = order_1[i]['date']
                       let email = order_1[i]['email']

                       let temp_html = ` <tr>
           <th scope="row">${name}</th>
           <td>${people}</td>
           <td>${date}</td>
           <td>${email}</td>
       </tr>   `
                       $('#hope_box').append(temp_html)

                   }

               }
           })
       }


   </script>
</head>

<body>
<div class="wrap">
   <div class="title_image"></div>
   <div class="title">
       <h1>가즈아~독일로!! <span class="price">비용:오만원!!/명 </span></h1>
       <p>독일은 인상적인 나라입니다. 독일 자연과 건축물의 놀라운 조화, 독특한 음식과 맥주, 흥미로운 역사를 상상해 보세요. 독일은 여러분의 눈과 입 그리고 마음까지 만족시켜드릴 것입니다. 유레일의 독일
           여행 일정은 독일의 주요 5개 도시로 안내해 드립니다. 초고층 건물에서부터 역사적인 랜드마크까지, 박물관에서부터 각종 파티까지, 유레일이 이 모든 멋진 경험들을 준비했습니다.
   </div>
   <div>
       <button class="btn_rate">오늘의 환율</button>
       <span id="rate"> ? </span>
   </div>
   <div>
       <div class="form-group">
           <label for="exampleFormControlInput1">갈 사람 누구?</label>
           <input type="email" class="form-control" id="exampleFormControlInput1">
       </div>
       <div class="form-group">
           <label for="exampleFormControlSelect1">몇 명?</label>
           <select class="form-control" id="exampleFormControlSelect1">
               <option>1</option>
               <option>2</option>
               <option>3</option>
               <option>4</option>
               <option>5</option>
           </select>

           <div class="form-group">
               <label for="exampleFormControlInput1">여행 희망일?</label>
               <input type="email" class="form-control" id="exampleFormControlInput2">
           </div>

           <div class="form-group">
               <label for="exampleFormControlInput1">안내받을 E-Mail?</label>
               <input type="email" class="form-control" id="exampleFormControlInput3" placeholder="name@example.com">
           </div>
           <button onclick="order()" class="btn">los geht's</button>
       </div>

   </div>
   <table class="table">
       <thead>
       <tr>
           <th scope="col">이름</th>
           <th scope="col">인원</th>
           <th scope="col">희망일</th>
           <th scope="col">E-Mail</th>
       </tr>
       </thead>
       <tbody id="hope_box">


       </tbody>
   </table>
</div>

</body>
</html>
profile
몰러유

0개의 댓글