이번 오픈SW플랫폼에서는 플라스크를 이용한 서비스의 백엔드를 구축하였다.
플라스크 애플리케이션의 코드는 기본적으로 웹 어플리케이션의 요청과 응답을 다루기 위한 라우팅을 정의한다. 코드의 주요 흐름은 다음과 같다.
라우팅 및 URL 매핑
@application.route()
데코레이터를 사용하여 특정 URL에 대한 요청을 처리하는 함수를 정의한. 각 라우트는 특정 URL 경로로 연결되어 있다.
pythonCopy code
@application.route("/")
def hello():
return render_template("index.html")
이 코드는 웹 애플리케이션의 루트 경로 ("/")에 대한 요청을 처리하며, hello()
함수가 실행되어 "index.html" 템플릿을 렌더링한다.
템플릿 렌더링
render_template()
함수를 사용하여 HTML 템플릿을 렌더링하고 클라이언트에 반환한다.
return render_template("index.html")
폼 데이터 처리
사용자가 웹 페이지에서 폼을 작성하고 제출하면, 해당 데이터는 POST 요청으로 서버로 전송된다. 이를 받기 위해 request
객체를 사용한다.
@application.route("/signup_post", methods=['POST'])
def register_user():
data = request.form
# 폼 데이터 처리...
데이터베이스 상호작용
DBhandler
클래스의 메서드를 사용하여 데이터베이스와 상호작용한다. 사용자 등록, 로그인, 상품 등록, 리뷰 등록 등의 작업은 해당 클래스의 메서드를 통해 데이터베이스에 반영된다.
if DB.insert_user(data, pw_hash):
return render_template("login.html")
else:
flash("user id already exist!")
return render_template("Signup.html")
session['id'] = id_
플라스크 앱 실행
if __name__ == "__main__":
블록을 사용하여 플라스크 앱을 실행한다.
pythonCopy code
if __name__ == "__main__":
application.run(host='0.0.0.0', debug=False)
전체 코드에 대해서 살펴보자.