[스파르타코딩클럽] 웹개발 종합반-4주차
Flask 프레임워크: 서버를 구동시켜주는 편한 코드 모음. 서버를 구동하려면 필요한 복잡한 일들을 쉽게 가져다 쓸 수 있습니다.
통상적으로 flask 서버를 돌리는 파일은 app.py라고 이름 짓습니다!
Flask 서버를 만들 때, 항상, 프로젝트 폴더 안에, ㄴstatic 폴더 (이미지, css파일을 넣어둡니다) ㄴtemplates 폴더 (html파일을 넣어둡니다) ㄴapp.py 파일 이렇게 세 개를 만들어두고 시작하세요.
-html 파일 불러오기
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 방식에 대해 다루겠습니다.
* GET → 통상적으로! 데이터 조회(Read)를 요청할 때 예) 영화 목록 조회 → 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달 → 예: google.com?q=북극곰
* POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때 예) 회원가입, 회원탈퇴, 비밀번호 수정 → 데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달
-GET 요청 API코드
@app.route('/test', methods=['GET'])
def test_get():
title_receive = request.args.get('title_give')
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
-GET 요청 확인 Ajax코드
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다",
data: {},
success: function(response){
console.log(response)
}
})
-POST 요청 API코드
@app.route('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
-POST 요청 확인 Ajax코드
$.ajax({
type: "POST",
url: "/test",
data: { title_give:'봄날은간다' },
success: function(response){
console.log(response)
}
})
-웹 스크롤링
import requests
from bs4 import BeautifulSoup
url = 'https://movie.naver.com/movie/bi/mi/basic.nhn?code=171539'
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)
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']
print(title,image,desc)
@app.route('/memo', methods=['POST'])
def saving():
url_receive=request.form['url_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')
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'] //위에 보이는 크롤링 부분
doc = {
'title':title,
'image':image,
'desc':desc,
'url': url_receive,
'comment':comment_receive
}
db.Articles.insert_one(doc) //인서트 부분
return jsonify({'msg':'저장이 완료되었습니다!'})
+ 4주차 숙제를 세 시간이나 헤매다가 해설강의를 보고 따라했다. 심지어 따라 했지만 그게 너무 이상해서 빨리 제출하고 체념...........ㅠㅠㅋ 그 뒤로 혼자 아직 해보지 않았는데 아직 절반도 못 따라 할 듯??????? 강의로 열심히 복습복습이 최선이다. 지금은....
***5만원 할인 링크 클릭!***
https://spartacodingclub.kr/?f_name=%EA%B9%80%EB%B3%B4%EC%9B%90&f_uid=6110d79e50065eacde984bab
스파르타코딩클럽
왕초보 8주 완성! 웹/앱/게임 빠르게 배우고 내것을 만드세요!
spartacodingclub.kr