티스토리 뷰
파이썬을 사용해 로컬 서버를 만드는 방법에 대해 배웠다.
일반적으로 서버를 만드는 작업은 매우 어려워서 'Flask'라는 프레임워크를 사용하여 만든다고 한다.
<Flask 기초>
1. 기본 폴더 구조(필수 세팅)
- static 폴더: 이미지, css파일을 넣어둔다.
- templates 폴더: HTML 파일을 담아두고, 불러오는 역할을 한다.
---> flask 내장함수 render_template를 이용한다.
- app.py 파일
위 3개의 파일을 만든 뒤 시작한다.(venv는 건들지 않기!!)
2. 연습 1 (GET 요청)
- 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=['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)
- index.html : templates 폴더 안에 생성
<!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>
3. 연습 2 (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=['GET'])
def test_get():
title_receive = request.args.get('title_give')
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
@app.route('/test', methods=['POST'])
def test_post():
title_receive = 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 : templates 폴더 안에 생성
<!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: "POST",
url: "/test",
data: {title_give: '봄날은간다'},
success: function (response) {
console.log(response)
}
})
}
</script>
</head>
<body>
<h1>나의 첫 웹페이지</h1>
<button onclick="hey()">여기는 버튼입니다.</button>
</body>
</html>
https://teamsparta.notion.site/4-cfc055cb19974e8aac0856a582ba3427
'[학습일지] > Python' 카테고리의 다른 글
[학습일지] 웹개발 3-10 ~ 3-16 ( MongoDB 기본 코드) (0) | 2022.07.16 |
---|---|
[학습일지] 웹개발 3-9 ( Python, requests/bs4) (0) | 2022.07.15 |
[학습일지] 웹개발 3-2 ~ 3-8 ( Python 입문, requests/bs4) (0) | 2022.07.14 |
[학습일지] 웹개발 3-1 ( Ajax, 영화 별점탭) (0) | 2022.07.13 |
[학습일지] 웹개발 2-14 ( Ajax, 날씨 정보) (0) | 2022.07.12 |