항해99_7기/사전 준비
[항해99] 사전준비-4 Flask 기초
code10
2022. 5. 2. 15:48
성취감이 있다. 서버에 적용시키는 게 재밌다. 하지만 헷갈린다. 연습이 많이 필요할 듯.
HTML > CSS > Bootstrap > Javascript >JQuery > API/Ajax > Python > Crawling > mongoDB > Flask(post,get) > 서버/AWS
배운 점: flask 서버 만들기, GET/POST 연습
어려운 점: GET/POST 코딩 짤 때 괄호들 ()와 {}, 따옴표 여부 '' 등이 헷갈린다. 연습이 많이 필요할 것 같다.
노트:
-POST는 app.py에서, GET은 index.html에서 다소 복잡
-✫Pymongo 패키지 + 꼭! Certifi 패키지도 설치(my컴 한정)
[Table] 강의: Flask 기초(API 만들기: POST, GET 방식 연습{화성땅, 스파르타피디아})(4-1~4-11)
강의 | 내용(내 기준, 알아둘 점) | 코드 예시 |
4-1 | 내 컴퓨터에서 만들고 내가 테스트해본다 >로컬개발환경 | |
4-2 | Flask 패키지 설치 Flask 프레임워크: 서버를 구동시켜주는 편한 코드 모음. (통상적) flask 서버를 돌리는 파일명: app.py |
|
4-3 * | Flask 서버 만들 때, 프로젝트 폴더 안에, directory(경로) 누르고, 2개 폴더 만들기(이름 고정) ⌙ templates 폴더 📁 (html 파일 넣기) ⌙ static 폴더 📁 (이미지, css 파일 넣기) ⌙ app.py 파일 서버 종료: 터미널 창에서 ctrl + c |
app.py에 render_template 적용 예시 (표 아래↓) |
4-4 | ||
4-5 | 프로젝트 설정 - flask 폴더 구조 만들기(static, templates 폴더 + app.py 만들기) 패키지 설치 - flask, pymongo, dnspython |
|
4-6 화성땅 공동구매 | ||
4-7** | POST 연습(주문 저장) 이름, 주소, 평수 저장하기(Create → POST) 1. 요청 정보 : URL= /mars, 요청 방식 = POST 2. 클라(ajax) → 서버(flask) : name, address, size 3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (주문 완료!) 서버부터 만들기(app.py) 클라이언트 만들기(index.html) ✫Pymongo 패키지 + 꼭! Certifi 패키지도 설치(my컴 한정) |
|
4-8 | GET 연습(주문 보여주기) 저장된 주문을 화면에 보여주기(Read → GET) 1. 요청 정보 : URL= /mars, 요청 방식 = GET 2. 클라(ajax) → 서버(flask) : (없음) 3. 서버(flask) → 클라(ajax) : 전체 주문을 보내주기 |
|
4-9 스파르타피디아 | ||
4-10 | meta tag 크롤링 | 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) |
4-11 | ||
4-12*** | POST 연습 | |
4-13**** | GET 연습 | |
4-14 homework | 팬명록 만들기(↓이미지) |
*4-3 app.py에 render_template 적용 예시
from flask import Flask, render_template
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)
**4-7 POST
서버부터 만들기(app.py)
@app.route("/mars", methods=["POST"])
def mars_post():
name_receive = request.form['name_give']
address_receive = request.form['address_give']
size_receive = request.form['size_give']
doc = {
'name': name_receive,
'address': address_receive,
'size': size_receive
}
db.orders.insert_one(doc)
return jsonify({'msg': '주문 완료!'})
클라이언트 만들기(index.html)
function save_order() {
let name = $('#name').val()
let address = $('#address').val()
let size = $('#size').val()
$.ajax({
type: 'POST',
url: '/mars',
data: { name_give:name, address_give:address, size_give:size },
success: function (response) {
alert(response['msg'])
window.location.reload()
}
});
}
***4-12 POST
서버 만들기
@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')
og_image = soup.select_one('meta[property="og:image"]')
og_title = soup.select_one('meta[property="og:title"]')
og_description = soup.select_one('meta[property="og:description"]')
image = og_image['content']
title = og_title['content']
description = og_description['content']
doc = {
'image':image,
'title':title,
'desc':description,
'star':star_receive,
'comment':comment_receive
}
db.movies.insert_one(doc)
return jsonify({'msg':'POST 연결 완료!'})
클라이언트 만들기
function posting() {
let url = $('#url').val()
let star = $('#star').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/movie',
data: {url_give: url, star_give: star, comment_give: comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
});
}
****4-13 GET
서버 만들기
@app.route("/movie", methods=["GET"])
def movie_get():
movie_list = list(db.movies.find({},{'_id':False}))
return jsonify({'movies':movie_list})
클라이언트 만들기
function listing() {
$('#cards-box').empty()
$.ajax({
type: 'GET',
url: '/movie',
data: {},
success: function (response) {
let rows = response['movies']
for(let i = 0; i < rows.length; i++) {
let image = rows[i]['image']
let title = rows[i]['title']
let desc = rows[i]['desc']
let star = rows[i]['star']
let comment = rows[i]['comment']
let star_image = '⭐'.repeat(star)
let temp_html = `<div class="col">
<div class="card h-100">
<img src="${image}"
class="card-img-top">
<div class="card-body">
<h5 class="card-title">${title}</h5>
<p class="card-text">${desc}</p>
<p>${star_image}</p>
<p class="mycomment">${comment}</p>
</div>
</div>
</div>`
$('#cards-box').append(temp_html)
}
}
})
}
4-14 homework