웹개발/수업

웹개발 4주차 개발일지_Sparta Coding Club

끈끈 2023. 3. 2. 13:12

 
4주차 수업 목표
 
1. Flask 프레임워크를 활용해서 API를 만들 수 있다.
 
2. '화성에 땅사기' API를 만들고 클라이언트에 연결한다.
 
3. '스파르타피디아' API를 만들고 클라이언트와 연결한다.
 


 
 Flask 시작하기 - 서버 만들기
 
Flask 프레임워크 : 서버를 구동시켜주는 편한 코드 모음
 
✔ 패키지 추가 설치하기(flask)
 
[설정] - [프로젝트] - [Python 인터프리터] - [+] - [flask 패키지 설치]
 
✔ flask 기본 폴더 구조
 
프로젝트 폴더 안에,
 
▶ static 폴더 👉 이미지, css 파일을 넣어둠
 
▶ templates 폴더 👉 html 파일을 넣어둠
 
▶ app.py 파일 👉 통상적으로 flask 서버를 돌리는 파일은 app.py라고 이름을 짓는다
 
✔ flask 시작 코드 (app.py)
 

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

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

 
✔ html 파일 불러오기 (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)

 


 
API 만들기
 
▶ GET : 데이터 조회(Read)를 요청할 때
 
데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
 
✔ GET 요청 API 코드
 

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

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

@app.route('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

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

 
✔ GET 요청 확인 Ajax코드
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function hey(){
            $.ajax({
                type: "GET",
                url: "/test?title_give=봄날은간다",
                data: {},
                success: function (response) {
                    console.log(response)
                }
            })
        }
    </script>
</head>
<body>
    <h1>나의 첫 웹페이지!</h1>
    <button onclick="hey()">나는 버튼이다</button>
</body>
</html>

 
▶ POST : 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청할 때
 
데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달
 
✔ 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)
    }
})

 


 

 

웹개발 4주차_화성땅 공동구매 프로젝트 연습

sparta → projects → mars 폴더에서 시작! ✔ flask 기본 폴더 구조 프로젝트 폴더 안에, static, templates 폴더, templates > index.html 파일, app.py 파일 생성 ✔ 패키지 설치하기 👉 Flask와 DB 연결 [설정] - [프로

sw-ing.tistory.com

 

 

웹개발 4주차_스파르타피디아 프로젝트 연습

sparta → projects → movie 폴더에서 시작! ✔ flask 기본 폴더 구조 프로젝트 폴더 안에, static, templates 폴더, templates > index.html 파일, app.py 파일 생성 ✔ 패키지 설치하기 👉 Flask와 DB 연결 [설정] - [프

sw-ing.tistory.com