본문 바로가기

Project/flask app 통신

[flask app 통신] app.py를 만들어보자

728x90

flask 서버와 ngrok을 이용한 배포 역할을 해주는 app.py를 만들어보겠습니다.

 

from flask import Flask, render_template, request, jsonify
from flask_ngrok import run_with_ngrok

 

먼저 필요한 라이브러리를 import 해준다.

 

app = Flask(__name__)

 

Flask 객체를 app에 저장해준다.

 

@app.route('/')
def hello_world():
    return "Hello Flask and Ngrok!"

 

route("경로") 함수를 사용하여 /로 요청이 오면 hello_world 함수가 실행될 수 있게 연결해준다.

 

@app.route('/test')
def test():
    return render_template('post.html')

 

마찬가지로 /test로 요청이 오면 test 함수가 실행될 수 있게 연결해준다. 이때 render_template를 사용하면 templates 폴더 안에 있는 post.html을 보여주게 된다.

 

@app.route('/post', methods=['POST'])
def post():
    if request.method == 'POST':
        value = request.form['test']
        return value

 

/post로 요청이 오면 post함수를 실행시켜주는 것은 동일하다. 하지만 route() 함수의 methods를 POST로 설정해주었으므로 /post로 온 POST 요청만 post 함수가 실행되게 된다.

 

@app.route('/send')
def send():
    return jsonify({
        "name": "alice",
        "age": 22,
        "sex": "female"
    })

 

/send로 요청이 오면 send 함수가 실행될 수 있게 연결해준다. 이때 jsonify는 결과를 json형태로 반환시켜준다.

 

run_with_ngrok(app)
app.run()

 

run_with_ngrok를 통해 app을 배포하고, app.run()을 통해서 서버를 열어준다.

728x90