티스토리 뷰

파이썬을 사용해 로컬 서버를 만드는 방법에 대해 배웠다.

일반적으로 서버를 만드는 작업은 매우 어려워서 '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

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함