- pymongo
1. mongoDB 에 데이터 저장하기 전 필수 요소
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://won:sparta@cluster0.4vhehoz.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
내 맥북에선 보안 오류가 나기 때문에 certifi 패키지 설치 필수 !! (pymongo, dnspython, certifi package)
2. mongoDB 에 데이터 조작 관련 소스코드
# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)
# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})
# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))
# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})
# 지우기 - 예시
db.users.delete_one({'name':'bobby'})
- Flask
[서버 만들기]
필요한 패키지 : Flask package + pymongo 기반 패키지
필요한 파일 틀 : static / templates ( index.html ) / app.py (db연동 소스코드 작성)
1. Flask 원리
| 1. Do (Ajax) : 내가 특정 조건에 해당하는 행동을 하면? ex) 버튼을 클릭, 새로고침 등 2. Flask : 서버에서 받아서 3. Show (Ajax) : loading 완료 후 행동에 대한 결과값을 보여준다 |
2. Flask 기본 폴더구조
| 프로젝트 폴더 안 ㄴstatic 폴더 (이미지, css파일을 넣어둡니다) ㄴtemplates 폴더 (html파일을 넣어둡니다) ㄴapp.py 파일 |
총 3가지의 기본 폴더구조를 구성한다 !필수!
3. Flask : html 파일 분리하기
| from flask import Flask, render_template 👉 내장함수 render_template를 이용 (선언 해줘야됨) app = Flask(__name__) ## URL 별로 함수명이 같거나, ## route('/') 등의 주소가 같으면 안됩니다. @app.route('/') def home(): return render_template('index.html') 👉 localhost:5000 실행 시 메인페이지 html 파일 지정 if __name__ == '__main__': app.run('0.0.0.0', port=5000, debug=True) |
4. Flask - API 만들기
👉 먼저, Jquery 임포트 해주기
| <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> |
👉 POST 요청 확인 Ajax코드 (데이터 생성, 변경, 삭제) / POST 요청 API코드
html 안 Ajax코드
| $.ajax({ type: "POST", url: "/프로젝트 폴더 이름", data: { 변수명_give : '//////////////' }, success: function(response){ console.log(response) } }) |
py파일 안 API코드
| @app.route('/test', methods=['POST']) def test_post(): title_receive = request.form['//////////////'] print(title_receive) return jsonify({'result':'success', 'msg': '------------'}) |
👉 GET 요청 확인 Ajax코드 (데이터 조회) / GET 요청 API코드
html 안 Ajax코드
| $.ajax({ type: "GET", url: "/test?title_give=//////////////", data: {}, success: function(response){ console.log(response) } }) |
py파일 안 API코드
| @app.route('/test', methods=['GET']) def test_get(): title_receive = request.args.get('///////////') print(title_receive) return jsonify({'result':'success', 'msg': '-------'}) |
'woncoding > TIL' 카테고리의 다른 글
| TIL | 9.5.월 [Python 언어의 이해 / Python 기초] (1) | 2022.09.05 |
|---|---|
| TIL | 9.2.금 [튜플 / 집합 / f-string / 예외처리 / 파일분리 / map, lambda, filter / class] (0) | 2022.09.02 |
| TIL | 9.1.목 [변수 / 리스트 / 딕셔너리 / 조건,반복문 / 함수] (0) | 2022.09.01 |
| TIL | 8.31.수 [1_mini_project] (0) | 2022.08.31 |
| TIL | 8.29.월 [Html / CSS / Javascript] (0) | 2022.08.29 |