1. mongo DB
: 브라우저에 데이터를 올려놓는 클라우드 서비스
$ pip install dnspython
$ pip install pymongo
설치 후 진행
$ pip install flask pymongo dnspython requests bs4
=> 한번에 설치
1-1. 기본 골격
from pymongo import MongoClient
client = MongoClient('여기에 URL 입력')
db = client.dbsparta
1-2. 데이터 설정
# 저장 - 예시
doc = {'name':'bobby','age':21} =>doc라는 임의의 변수
db.users.insert_one(doc)
# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'}) =>users는 몽고db에서 만든 파일이름
# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))
# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})
# 지우기 - 예시
db.users.delete_one({'name':'bobby'})
2. Flask
` app.py 폴더(백엔드) 생성후 , 가상환경을 설정한다.
$python -m venv venv
` 프레임워크를 설치한다.
$pip install flask
`templates 폴더를 만들어서 삽입할 html파일을 만든다.
1. Flask 시작코드
from flask import Flask
app = Flask(__name__)
@app.route('/') => route 안의 값은 창구를 만들 수 있는곳 ex) localhost:5000/route안의 값
def home():
return 'This is Home!' =>화면에 표출값, html로도 표현 가능하다
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
2. < GET 방식 > HTML 파일 가져오기
Q) GET방식이란? 통상적으로 데이터 조회를 요청할 때 사용
<백엔드 app.py>
from flask import Flask, render_template, request , jsonify
app = Flask(__name__) => html가져옴 => GET방식에 필요
@app.route('/')
def home():
return render_template('index.html') =>index.html 파일을 render_template로 가져옴
@app.route('/test', methods=['GET']) =>GET 요청으로 들어온다. 어디로? /test라는 창구로
def test_get():
title_receive = request.args.get('title_give') => 'title_give 라는 변수가 있으면 title_receive 에다가 넣자
print(title_receive) => 그리고 title_receive 를 프린트해보자
return jsonify({'result':'success', 'msg': '이 요청은 GET!'}) => 백엔드에서 프론트엔드로 데이터를 내려준다
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
<프론트 엔드 index.html>
<script>
function hey() {
fetch("/test").then(res => res.json()).then(data => { => /test 라고 하는 url 에다가 요청을 해서 데이터를 받고
console.log(data) => 콘솔에 찍자
})
}
</script>
3. < POST 방식 > HTML 파일 가져오기
Q)POST방식이란? 통상적으로 데이터 생성, 변경, 삭제 요청할 때 사용
<백엔드 app.py>
from flask import Flask, render_template, request , jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/test', methods=['POST']) =>test에서 프론트에서 보낸 데이터를 받음
def test_post():
title_receive = request.form['title_give'] => request.form['title_give'] 가 '블랙팬서'가 됨 (프론트에서 받았기때문)
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'}) =>다 끝났으니 이 문장을 내려줘라
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
<프론트 엔드 index.html>
<script>
function hey() { => hey()를 누르면 뭔가 데이터가 쌓임
let formData = new FormData();
formData.append("title_give", "블랙팬서");
fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => {
console.log(data) => 그 데이터를 가지고 /test 에다가 보냄
})
}
</script>
</head>
<body>
<button onclick="hey()">나는 버튼!</button>
</body>
'Knowledge > sparta web develope' 카테고리의 다른 글
project. 화성땅 공동구매 (1) | 2023.05.12 |
---|---|
CSS, 깃허브 (0) | 2023.05.11 |
파이썬 기본 , 웹스크래핑(크롤링) (0) | 2023.05.09 |
Fetch 데이터 가져오기 (0) | 2023.05.08 |
Javascript & JQuery (0) | 2023.05.08 |