SERVER/FLASK
flask를 이용해 개발하다 느낀 것
도오라에몽
2023. 5. 10. 23:03
보통 flask든 node.js든 간단한 예제를 보면 아래와 같은 형식을 보여주게 된다.
@app.router('/')
def hello():
return render_template('index.html')
@app.router('/node1', methods=["GET"])
def node1_get():
return render_template('node1.html')
@app.router('/node1', methods=["POST"])
def node1_post():
return "node1_post"
그리고 보통 페이지를 구성할 때 /
와 /node1
에 해당하는 페이지를 구성해서 보여준다.
그래서 나도 페이지를 만들 때 url을 노드에 해당되게 만들었다.
하지만 저 방식을 따라하게 되니 내가 구현하고 싶은 동작을 구현하지 못하는 문제가 발생하였고 어떤 구조로 짜는게 좋은지 내가 착각하고 있는 부분은 없는지 생각하게 되었고 간단한 데이터 흐름을 하나씩 파악하여 다른 방식으로 원하는 동작을 구현하게 되었다.
위의 예제처럼 node1
에 해당하는 페이지를 node1
에서 get 방식으로 값을 받아오는 것이 아니라 아래 방식으로 전용 처리 api를 만들어서 데이터 입출력을 따로 하게 만들었다.
@app.router('/')
def hello():
return render_template('index.html')
@app.router('/node1', methods=["GET"])
def node1():
return render_template('node1.html')
@app.router('/fetchdb', methods=["GET"])
def fetchdb_get():
handle_data()
return jsonify({ 'msg':'loading data success' })
@app.router('/fetchdb', methods=["POST"])
def fetchdb_post():
handle_data()
return jsonify({ 'msg':'saving data success' })
위의 방식대로 만들면 node1
페이지를 정상적으로 불러들이면서 웹 클라이언트에 있는 자바스크립트가 fetch(fetchdb)
를 하게 되면 데이터를 정상적으로 수신받을 수 있다. 꼭 node1
페이지라고 해서 @app.router('/node1')
을 이용할 필요는 없는 것 같다.
서버를 처음 공부하다보니 혹시 몰라 기록을 남긴다.