그저 내가 되었고

📚지금까지 헷갈리는 것 정리 본문

개발/항해99 9기

📚지금까지 헷갈리는 것 정리

hyuunii 2022. 9. 9. 17:35

🏐🐈

最初リアできそうにないゲームでも、

繰り返すうちに慣れるんだよ


 

🍋let value = $('#input-q1').val();이건 let (value, email, name..... 아무거나 네 마음대로 변수 네이밍해주는거야) = $('_____').val();

 

🍎let temp_html = `<li>${newName}</li>`; 에서 temp_html 의미? '나 전달하고싶은/쓰고싶은 데이터가 있어'라는 뜻이고, let 그렇게 하라는거지. 그니까 let(temp_html)은 그렇게 해(네가 전달하고싶은거) =그건 바로= `(이거야)`

 

🥭let temp_html = `....${image}....` 이건 일단 자바스크립트 문법이니까, $달러 콜링(자바스크립트의) 후 위에서 for문으로 정의해준 let image = ~에서 좌변의 image 불러오는 것

 

🍑$('#names-q3').append(temp_html); 이건 "야 자바스크립트($ 달러 콜링), id가 names-q3에다가 내가 전달하고싶은 거(temp_html)를 append(선택한 요소 즉 names-q3의 내용 끝에 컨텐츠를 추가해줘)"이거임.

※위의 두 개로 미루어 볼 때, 달러 콜링에서 id값은 $('#여기')에 쓰고, 변수는 ${여기}에 쓰는 것 같음!!!

 

🍒$.ajax({... 이건? 에이젝스 콜, 자바스크립트→서버를 요청(브라우저에서 엔터 치는 것과 마찬가지) 

$.ajax({
  type: "GET",  // GET 방식으로 요청할게
  url: "/test?title_give=봄날은간다",  //요청할 url(test라는 창구에 가는데, title_give라는 이름으로(학번이라는 이름으로) 봄날은간다는 데이터를(학번을) 갖고 갈게 
  data: {},  // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
  success: function(response){  // 성공하면 response 변수값에 서버의 결과 값을 담아서 함수를 실행한다.
    console.log(response)  // 서버에서 준 결과를 이용해서 나머지 코드를 작성
  }
})

 

+ 🍐 @app.route('/')...이건? 플라스크→클라이언트

@app.route('/test', methods=['GET'])   // /test라는 창구에서 받을건데
def test_get():
title_receive = request.args.get('title_give')   // title_give라는 이름으로 뭔가를 받아와서 title_receive라는 변수에 넣고
print(title_receive)   // 그 변수를 찍어줬어
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

 

🍉 css에서는 선택자로 classjQuery에서는 id값 css와 마찬가지로, jQuery를 쓸 때에도 "가리켜야" → 조작할 수 있음. css에서는 선택자로 class를 썼다면, jQuery에서는 id값을 통해 특정 버튼/인풋박스/div/.. 등을 가리킴.

 

🍪 CLASS vs ID

중복 사용 여부 클래스는 중복 사용이 가능하여, 동일한 클래스명을 페이지의 여러 곳에 사용해도 무방. 아이디는 중복으로 사용할 수 없다. 한 개의 아이디는 페이지에서 딱 한번만 사용해야 한다. 

한 요소가 갖는 갯수 제한 여부 클래스(class)의 경우에는 한 요소에 여러개의 클래스명이 적용될 수 있고 각각은 띄어쓰기로 구분. 아이디(id)는 한 요소에 한 아이디만 적용이 가능.

정리 여러가지 스타일링을 한꺼번에 적용해야 할 때는 클래스(class)를 사용하고, 한가지만 적용하고 싶다면 아이디(id)를 사용. -e.g.<div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">

 

🍡let star_image = '⭐'.repeat(star)

 

🍭만약 부트스트랩에서 갖고온것에 input id 주려는데 처음부터 floatingInput 뭐 이런 이름 되어있으면 그냥 지우고 막 바꿔도 됨(WHY? 부트스트랩 애들은 class 값으로 종류가 달라짐(예시 https://mement-m0ri.tistory.com/51)

e.g.)

<div class="form-floating mb-3">
    <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
    <label for="floatingInput">영화 URL</label>
</div>
👇🏻👇🏻
<div class="form-floating mb-3">
    <input type="email" class="form-control" id="URL" placeholder="name@example.com">
    <label for="floatingInput">영화 URL</label>
</div>

 

🍮Beautifulsoup 사용 中 태그 안의 텍스트? 태그.text vs태그 안의 속성? 태그['속성']or태그["속성"] -e.g.) print (a.text), rank = movie.select_one('td:nth-child(1) > img')['alt'], gourmet.select_one('div > a > span > img')["src"]

 

🍧크롤링 사전 준비

1] 두 개 설치 : 주소 찍고 그 웹페이지 html 가져오는 것(requests로 할 것) & 그 안에서 제목 등 필요한 정보 찾는 것(beautifulsoup)

2] 파이썬 파일 준비: 크롤링 기본 세팅 app.py에 붙여넣기👇🏻

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient

client = MongoClient(
    'mongodb://test:sparta@ac-qs2cnvy-shard-00-00.u33zjtg.mongodb.net:27017,ac-qs2cnvy-shard-00-01.u33zjtg.mongodb.net:27017,ac-qs2cnvy-shard-00-02.u33zjtg.mongodb.net:27017/Cluster0?ssl=true&replicaSet=atlas-4g7ly1-shard-0&authSource=admin&retryWrites=true&w=majority')
db = client.dbsparta

url = 'https://www.siksinhot.com/taste?upHpAreaId=9&hpAreaId=&isBestOrd=Y'

# 타겟 URL을 읽어서 HTML를 받아오고,
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url, headers=headers)

# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
# soup이라는 변수에 "파싱 용이해진 html"이 담긴 상태가 됨
# 이제 코딩을 통해 필요한 부분을 추출하면 된다.
soup = BeautifulSoup(data.text, 'html.parser')

#############################
# (입맛에 맞게 코딩)
#############################

(👆🏻여기선 url을 서버 구축할때 직접 써줬지만, 클라이언트에서 GET으로 URL을 받아 오고 그걸로 크롤링 하게끔 할 수도 있음. 그 때는 위의 코드에서 url=~이 부분 자체가 빠지고, 아래처럼 url_receive가 될 것)

@app.route("/movie", methods=["POST"])
def movie_post():
    url_receive = request.form['url_give']
    star_receive = request.form['star_give']
    comment_receive = request.form['comment_give']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    return jsonify({'msg':'POST 연결 완료!'})

(👆🏻headers=~, data=~, soup=~가.. 좀 애매한 곳에 있는 것 같았는데 바로 위의 코드의 주석을 보니 쟤들 세개는 확실히 '크롤링'을 위한 것. 그러니 크롤링이 필요한 순간 그 바로 '직전'에 쟤들을 써주는걸로 충분할 듯)

3] 크롤링 시작: 기본 세팅에서, url만 내가 긁을 페이지로 바꿔 가면서 사용하면 됨(아니면 클라에서 받던가)

4] mongodb 저장하려면 인터프리터 dnspython, pymongo 설치 필요(2] 밑의 코드에 다 붙어있음. 인터프리터 설치 必)

 

🍓POST & GET 사전 준비

1] 원하는 위치에 새폴더 만들기

2] 새 프로젝트 생성 > 만든 폴더 클릭> venv 붙어있는지 체크 및 웰컴스크립트 박스 해제되었는지 체크 후 생성

3] flask 폴더 구조 만들기(프로젝트 설정하기, 총 4개): 새로 만들기 > 경로 > static, 새로 만들기 > 경로 > templates & templates 안에 index.html, 새로 만들기 > python파일 > app.py

4] 패키지 설치하기(총 3개): 설정 > 프로젝트: (폴더명) > + 클릭 후 flask, pymongo, dnspython 설치

5] flask 프레임워크 사용 위한(for 서버 구동) app.py 뼈대 코드 준비👇🏻(💡🤔 flask? 크롬에서 http://localhost:5000/ 으로 접속 가능해짐!)

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

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

@app.route("/movie", methods=["POST"])
def movie_post():
    sample_receive = request.form['sample_give']
    print(sample_receive)
    return jsonify({'msg':'POST 연결 완료!'})

@app.route("/movie", methods=["GET"])
def movie_get():
    return jsonify({'msg':'GET 연결 완료!'})

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

 6] index.html 뼈대 코드 준비

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

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

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>타이틀</title>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .mytitle {
            width: 100%;
            height: 250px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg');
            background-position: center;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mytitle > button {
            width: 200px;
            height: 50px;

            background-color: transparent;
            color: white;

            border-radius: 50px;
            border: 1px solid white;

            margin-top: 10px;
        }

        .mytitle > button:hover {
            border: 2px solid white;
        }

        .mycomment {
            color: gray;
        }

        .mycards {
            margin: 20px auto 0px auto;
            width: 95%;
            max-width: 1200px;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px auto;
            padding: 20px;
            box-shadow: 0px 0px 3px 0px gray;

            display: none;
        }

        .mybtns {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }

        .mybtns > button {
            margin-right: 10px;
        }
    </style>
    
    <script>
        $(document).ready(function () {
            listing();
        });

        function listing() {
            $.ajax({
                type: 'GET',
                url: '/movie',
                data: {},
                success: function (response) {
                    alert(response['msg'])
                }
            })
        }

        function posting() {
            $.ajax({
                type: 'POST',
                url: '/movie',
                data: {sample_give: '데이터전송'},
                success: function (response) {
                    alert(response['msg'])
                }
            });
        }

        function open_box() {
            $('#post-box').show()
        }

        function close_box() {
            $('#post-box').hide()
        }
    </script>
</head>

<body>
<div class="mytitle">
    <h1>내 생애 최고의 영화들</h1>
    <button onclick="open_box()">영화 기록하기</button>
</div>
<div class="mypost" id="post-box">
    <div class="form-floating mb-3">
        <input id="url" type="email" class="form-control" placeholder="name@example.com">
        <label>영화URL</label>
    </div>
    <div class="input-group mb-3">
        <label class="input-group-text" for="inputGroupSelect01">별점</label>
        <select class="form-select" id="star">
            <option selected>-- 선택하기 --</option>
            <option value="1">⭐</option>
            <option value="2">⭐⭐</option>
            <option value="3">⭐⭐⭐</option>
            <option value="4">⭐⭐⭐⭐</option>
            <option value="5">⭐⭐⭐⭐⭐</option>
        </select>
    </div>
    <div class="form-floating">
        <textarea id="comment" class="form-control" placeholder="Leave a comment here"></textarea>
        <label for="floatingTextarea2">코멘트</label>
    </div>
    <div class="mybtns">
        <button onclick="posting()" type="button" class="btn btn-dark">기록하기</button>
        <button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button>
    </div>
</div>
<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

</html>

 

🍰웹서비스 런칭·배포 사전 준비

1] Filezilla: (설치) 직접 만든 소스(?)들을 서버로 올려주는 프로그램

2] 가비아: 도메인 구매(___.shop)

3] AWS: 서버 사용권(EC2 사용권) 구매(AWS는 클라우드 서비스)

4] Git Bash: (설치) AWS에서 산 서버 EC2의 OS는 Ubuntu임. Window에서 Linux의 명령어를 쓰려면 Git Bash가 필요함.

 (git bash 는 window 의 cmd, linux와 mac 의 terminal과 같은 역할을 한다. 그러나 운영체제마다 명령어가 다르다는 문제점이 있는데, 이를 극복한것이 바로 Git bash!! 얘를 이용하면 window 에서도 리눅스의 명령어를 쓸 수 있다.)