728x90

내가 웹 개발 자신있다. 혼자 할수있다고 말할 수 있게 공부하자.

복습!좀 해랑...

 

이론복습

1.클라이언트 

: 브라우저, 핸드폰

요청을 하는쪽

 

2. 서버

API라는 창구를 통해서 클라이언트와 소통함

ex)은행의 창구

-규칙들로 요청을 받는쪽

-요청을 받고 돌려줄때 json이라는 형태로 돌려줌

- 서버는 컴퓨터의 역할

 

○ API란? = 창구

-POST :데이터수정

-GET :수정없이 가져올때

 

html : 뼈대

css: 꾸미기 

javascript : 움직이게 하는것

 

JQUERY 

javascript의 라이브러리로, 남이만들어놓은 갖다쓰기 좋은 코드, html조작 쉽게 함.

id로 이름표붙여주고, $('아이디').val()과 같이 input박스의 값을 가져옴

 

Ajax

- 서버통신을 위해 쓰이는것 (클라이언트로 요청보내고, 요청에 대한 대답받아옴)

$.ajax({
    type: "GET",
    url: "요청할 URL",
    data: {},
    success: function (response) {
        // 서버가 준 데이터가 response에 담깁니다!
    }
})

클라이언트에서 서버에 요청을 코드로 할수있게(화면전환없이)

 

 

 

Flask

- 파이썬으로 서버 프레임워크 틀 만들어둔 것.

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

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

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

요런식으루


프로젝트 세팅 복습

- templates,static폴더 만들고, app.py파일 만들기

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

크롤링 세팅
import requests
from bs4 import BeautifulSoup

mongoDB쓰기 위해서 꼭 3줄 세팅
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

## HTML을 주는 부분
@app.route('/')
def home():
   return render_template('index.html')

@app.route('/memo', methods=['GET'])
def listing():
    articles = list(db.articles.find({}, {'_id': False}))
    return jsonify({'all_articles':articles})

## API 역할을 하는 부분
post api
@app.route('/memo', methods=['POST'])
def saving():
    url_receive = request.form['url_give']
    comment_receive = request.form['comment_give']
클라이언트로부터 url과 comment받음

크롤링하는부분
    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')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

DB에 저장하는 코드
    doc = {
        'title':title,
        'image':image,
        'desc':desc,
        'url':url_receive,
        'comment':comment_receive
    }

    db.articles.insert_one(doc)

    return jsonify({'msg':'저장이 완료되었습니다!'})

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)
<!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">

        <!-- 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>

        <!-- 구글폰트 -->
        <link href="https://fonts.googleapis.com/css?family=Stylish&display=swap" rel="stylesheet">


        <title>스파르타코딩클럽 | 나홀로 메모장</title>

        <!-- style -->
        <style type="text/css">
            * {
                font-family: "Stylish", sans-serif;
            }

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

            .comment {
                color: blue;
                font-weight: bold;
            }

            #post-box {
                width: 500px;
                margin: 20px auto;
                padding: 50px;
                border: black solid;
                border-radius: 5px;
            }
        </style>
        <script>
            $(document).ready(function () {
                showArticles();
            });

            function openClose() {
                if ($("#post-box").css("display") == "block") {
                    $("#post-box").hide();
                    $("#btn-post-box").text("포스팅 박스 열기");
                } else {
                    $("#post-box").show();
                    $("#btn-post-box").text("포스팅 박스 닫기");
                }
            }

            function postArticle() {
                let url = $('#post-url').val()태그에서 값 가져옴
                let comment = $('#post-comment').val()태그에서 값 가져옴
				
                가져온 값을 ajax콜에다가 태움
                $.ajax({
                    type: "POST",
                    url: "/memo",
                    data: {url_give:url, comment_give:comment},
                    success: function (response) { // 성공하면
                    받아온값을 alert로 띄워줌
                        alert(response["msg"]);
                        window.location.reload()
                    }
                })
            }

            function showArticles() {
                $.ajax({
                    type: "GET",
                    url: "/memo",
                    data: {},
                    success: function (response) {
                        let articles = response['all_articles']
                        for (let i = 0; i < articles.length; i++) {
                            let title = articles[i]['title']
                            let image = articles[i]['image']
                            let url = articles[i]['url']
                            let desc = articles[i]['desc']
                            let comment = articles[i]['comment']

                            let temp_html = `<div class="card">
                                                <img class="card-img-top"
                                                     src="${image}"
                                                     alt="Card image cap">
                                                <div class="card-body">
                                                    <a target="_blank" href="${url}" class="card-title">${title}</a>
                                                    <p class="card-text">${desc}</p>
                                                    <p class="card-text comment">${comment}</p>
                                                </div>
                                            </div>`
                            $('#cards-box').append(temp_html)
                        }
                    }
                })
            }
        </script>

    </head>

    <body>
        <div class="wrap">
            <div class="jumbotron">
                <h1 class="display-4">나홀로 링크 메모장!</h1>
                <p class="lead">중요한 링크를 저장해두고, 나중에 볼 수 있는 공간입니다</p>
                <hr class="my-4">
                <p class="lead">
                    <button onclick="openClose()" id="btn-post-box" type="button" class="btn btn-primary">포스팅 박스 열기
                    </button>
                </p>
            </div>
            <div id="post-box" class="form-post" style="display:none">
                <div>
                    <div class="form-group">
                        <label for="post-url">아티클 URL</label>태그 발견!
                        <input id="post-url" class="form-control" placeholder="">
                    </div>
                    <div class="form-group">
                        <label for="post-comment">간단 코멘트</label>
                        <textarea id="post-comment" class="form-control" rows="2"></textarea>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="postArticle()">기사저장</button>
                </div>
            </div>
            <div id="cards-box" class="card-columns">
            </div>
        </div>
    </body>

</html>

나홀로 일기장

부트스트랩: 남이만들어놓은 css

ctrl+/ :  주석

 

GET하고 POST 방식쓰는게 헷갈린다

이 나홀로 일기장 코드쓸때

POST는 사용자한테 입력받아서 DB에 저장 -> 서버에 전달 ajax id값을 가져와서 저장시킴

GET은 DB에 저장된 데이터를 가져와서 보여줌 ( 응답에서 원하는값 찾아서 카드 템플릿에 값 대입)

 

카드에 이미지 넣는방법: 

static폴더에 이미지 하나 저장하고 경로로 불러와줌

이미지를 불러와서 로드하였을때 입력란에 이미지에 대한 경로나 정보가 뜨게!

 

앗, 그런데 선택한 파일이 안보여요! → 이것은 특별한 라이브러리를 임포트 해달래요! (누가? - 부트스트랩 만든이 사람이!)

파일업로드 라이브러리

<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script

파일업로드 코드

bsCustomFileInput.init()


파일업로드가 동작하도록 하는법

앞서 title과 content를 받은것처럼 

받아와야하는데 조금 형태가 다름

서버

file = request.files["file_give"]

save_to = 'static/mypicture.jpg'
file.save(save_to)

파일은 앞서 했던 방식으로 보내기가 어려움

클라이언트

function posting() {
    let title = $('#title').val()
    let content = $("#content").val()

    let file = $('#file')[0].files[0]
    let form_data = new FormData()

    form_data.append("file_give", file)
    form_data.append("title_give", title)
    form_data.append("content_give", content)

    $.ajax({
        type: "POST",
        url: "/diary",
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            alert(response["msg"])
            window.location.reload()
        }
    });
}

 

FormData에 태워서 보냄

let file = $('#file')[0].files[0]

는 file이 품고있는 여러 속성중에 0번째이며, files라고하면 들어가있는 파일들의 갯수가 나오므로 0번째로 해야 젤 첫번째꺼

 


새로운 문법배우깅

f-string

name = '홍길동'
age = '30'

hello = f'제 이름은{name}입니다. 나이는 {age}입니다'

 

날짜

from datetime import datetime

today = datetime.now()
mytime = today.strftime('%Y-%m-%d-%H-%M-%S')

filename = f'file-{mytime}'
print(mytime)

 

응용하기

서버

filename = f'file-{mytime}'
extension = file.filename.split('.')[-1]
#가장마지막 .뒤에 글자 가져오면 확장자 가져올 수 있음

save_to = f'static/{filename}.{extension}'
file.save(save_to)

doc= {
'title' : title_receive,
'content':content_receive,
'file':f'{filename}.{extension}' -->title,contetn에 맞게 파일 대응시킴 

}

확인가능

 

완성본

ㅎㅎ

갑자기 수업이 2배로 재밌어짐 

사심채우기..ㅎㅎ

 


EC2서버를 사서 올려놓깅!

인스턴스 -> 인스턴스 시작 -> 키페어 다운로드 -> 인스턴스 생성!

 

원격접속하려면 

git bash실행

ssh -i 키페어끌어옴 인스턴스주소

원격접속 완료, 띄어쓰기 잘하자.

 

포트열기

보안 -> 보안그룹->인바운드규칙편집 -> 규칙추가 (포트추가, 위치무관)

 

filezila열기

설정 완료(이전에 작성한 게시물에 있음)하고 연결하면

우측이 구입한 것, 왼쪽이 본인 컴퓨터

스파르타 측에서 정리해놓은 파일 다운로드 함

우측으로 그 파일옮겨줌

 

gitbash에서

 

그럼 쫙~깔림

mongo가 깔렸나 확인 mongo쳐보면됨

exit하면 bye~

 

 

robo 3T에서 새롭게 생성 후 연결

address에는 아이피주소,

id,pw에는 test,test

연결!

 

 

내 로컬에서 실행할때

client = MongoClient('localhost', 27017)

올릴때

client = MongoClient('mongodb://test:test@localhost', 27017)

추가해주공

 

filezila에다가 project01의 static,templates, app.py옮겨주고, 

static의 사진들 다 지워줌 필요없으니까

 

git bash에서 확인

app.py여기서 열려면 flask랑 그런거 깔아줘야함

pip install flask

pip install pymongo

python app.py

실행해주고

 

크롬에 아이피주소:5000해보면! 잘뜸

 

원격접속끊어도 계속 돌아가게하기

nohup python app.py &

 

돌아가는거 끄기

ps -ef | grep 'app.py'

kill -9 20*** (숫자 사람마다 다름)

kill -9 20***

 


도메인 설정

https://www.gabia.com/login/login_form?redirect=1&origin_site=https://my.gabia.com&target_url=%2Fservice#/ 

 

웹을 넘어 클라우드로. 가비아

그룹웨어부터 멀티클라우드까지 하나의 클라우드 허브

www.gabia.com


1주차 완료 코드

index.html

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

<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>스파르타코딩클럽 | 부트스트랩 연습하기</title>
    <script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>
    <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=Jua&display=swap" rel="stylesheet">
</head>
<style>
    * {
        font-family: 'Jua', sans-serif;
    }

    .posting-box {
        width: 500px;
        margin-top: 20px;

    }

    .container {
        padding-left: 50px;
        /*여백을줌*/
    }

    .wrap {
        width: 900px;
        margin: auto;

    }
    .posting-box > .custom-file {
        margin-bottom: 20px;
    }

</style>
<script>
    $(document).ready(function () {
        bsCustomFileInput.init()
        listing()
    })

    function listing() {
        $.ajax({
            type: "GET",
            url: "/diary",
            data: {},
            success: function (response) {
                let diaries = response['all_diary']
                for (let i = 0; i < diaries.length; i++) {
                    let title = diaries[i]['title']
                    let content = diaries[i]['content']
                    let file = diaries[i]['file']
                    let time = diaries[i]['time']

                    let temp_html = `<div class="card">
                                        <img src="../static/${file}" class="card-img-top">
                                        <div class="card-body">
                                            <h5 class="card-title">${title}</h5>
                                            <p class="card-text">${content}</p>
                                            ${time}
                                        </div>
                                    </div> `
                    $('#cards-box').append(temp_html)
                }
            }
        })
    }
    function posting() {
    let title = $('#title').val()
    let content = $("#content").val()
    let file = $('#file')[0].files[0]
    let form_data = new FormData()

    form_data.append("file_give", file)
    form_data.append("title_give", title)
    form_data.append("content_give", content)

    $.ajax({
        type: "POST",
        url: "/diary",
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            alert(response["msg"])
            window.location.reload()
        }
    });
}

</script>


<body>
<!--전체를 감싸는 클래스 만들어서 크기 조정해주기 -->
<div class="wrap">
    <div class="jumbotron jumbotron-fluid">
        <div class="container">
            <h1>나홀로 일기장</h1>
            <div class="custom-file">
                <input type="file" class="custom-file-input" id="file">
                <label class="custom-file-label" for="file">사진 선택하기</label>
            </div>
            <div class="posting-box">
                <div>
                    <div class="form-group">

                        <input type="email" class="form-control" id="title" placeholder="사진 제목">
                    </div>
                    <div class="form-group">

                        <textarea class="form-control" id="content" rows="3"
                                  placeholder="내용 입력"></textarea>
                    </div>
                </div>
                <button onclick="posting()" type="submit" class="btn btn-primary">저장하기</button>
            </div>

        </div>
    </div>
    <div class="card-columns" id="cards-box">

    </div>
</div>
</body>


</html>

app.py

from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
#client = MongoClient('mongodb://test:test@localhost', 27017)
db = client.dbsparta_plus_week1
from datetime import datetime
@app.route('/')
def home():
    return render_template('index.html')

@app.route('/diary', methods=['GET'])
def show_diary():
    diaries = list(db.diary.find({}, {'_id': False}))
    return jsonify({'all_diary': diaries})
    # 내려줌, 값을 담는 변수 생성

@app.route('/diary', methods=['POST'])
def save_diary():
    title_receive = request.form['title_give']
    content_receive = request.form['content_give']
    file = request.files["file_give"]

    today = datetime.now()
    mytime = today.strftime('%Y-%m-%d-%H-%M-%S')

    filename = f'file-{mytime}'
    extension = file.filename.split('.')[-1]
    #가장마지막 .뒤에 글자 가져오면 확장자 가져올 수 있음


    save_to = f'static/{filename}.{extension}'
    file.save(save_to)

    doc= {
        'title' : title_receive,
        'content':content_receive,
        'file':f'{filename}.{extension}',
        'time': f'{mytime}'
    }
    db.diary.insert_one(doc)

    return jsonify({'msg':'저장완료!'})
if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)

후하!

728x90

'✍2021,2022 > WEB' 카테고리의 다른 글

3주차 개발일지~!  (0) 2021.07.26
웹개발+/2주차 필기,개발일지  (0) 2021.07.18
5주차 필기/개발일지  (0) 2021.07.01
4주차 개발/필기일지  (0) 2021.07.01
3주차 필기/개발일지  (0) 2021.06.20
리촬리