728x90
1. 패키지 설치
가상환경을 세팅한 후 python interpreter에 pip install flask 입력하여 설치
2. 폴더 구조
폴더명 | 설명 |
.venv | 가상환경 설정 폴더(건들지 않는다.) |
static | html을 제외한 css관련 이미지 등의 파일들을 담아두는 폴더 |
templates | html 파일들을 담아두는 폴더(app.py 폴더에 render_template 를 import하여 사용) |
app.py | flask 서버를 돌리는 파일 |
3. app.py 기본 코드 -- 서버코드
from flask import Flask, jsonify,render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('test.html')
# /test : url/test
# GET
@app.route('/test', methods=['GET'])
def test_get():
return jsonify({'result':'success', 'msg':'GET'})
# Post
@app.route('/test', methods=['POST'])
def test_post():
return jsonify({'result': 'success', 'msg':'POST'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
4. flask에 사용되는 HTML 파일 주의사항 -- 클라이언트코드
<img src="{{ url_for('static', filename='test.jpg') }}"/>
위의 코드와 같이 flask를 사용할 때 {{ }} 내의 내용처럼 써서 flask가 html 정보를 내보낼 때 알맞게 보낸다.
<!Doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<!-- JS -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<title> test </title>
<!-- style -->
<style type="text/css">
<!-- 적용할 스타일 -->
</style>
<script>
$(document).ready(function () {
//페이지 로딩 후 실행화면
getTest();
});
function postTest() {
$.ajax({
type: "POST",
url: "/test",
//즉, 요청할 때 줄 데이터
data: {},
success: function (response) {
//성공시 실행할 명령어
if (response['result'] == 'success') {
let msg = response['msg'];
alert(msg);
}
}
})
}
function getTest() {
$.ajax({
type: "GET",
url: "/test",
data: {},
success: function (response) {
//성공시 실행할 명령어
if (response['result'] == 'success') {
let msg = response['msg'];
alert(msg);
}
}
})
}
</script>
</head>
<body>
<button type="button" onclick="postTest()">post 버튼</button>
</body>
</html>
5. 실제 실행 화면
계속해서 python 코드를 실행중이라서 Process finished with exit code 0. 가 뜨지 않는다. 종료하길 원하면 ctrl+c(맥북도 동일)
Running on http:// 본인 IP주소:5000 의 주소를 chrome으로 실행하면
※ 맥북 사용자는 5000번 포트가 사용중이라고 뜬다.
※ https://algoroot.tistory.com/44 참고하여 5000번 포트를 비워준다.
728x90
'Language > Python' 카테고리의 다른 글
[Python] Stack과 Queue사용해보기 (0) | 2023.03.21 |
---|---|
[Python] 리스트(List) 개념 정리 (0) | 2023.03.20 |
[Python] pymongo를 이용하여 mongoDB 사용해보기 (0) | 2023.02.14 |
[Python] 가상환경 설정하기 (0) | 2023.02.11 |