SGS 사전과제를 진행하며 스택으로 Python+Flask를 선택해 조금 더 자세히 다뤄보게 되었습니다. 그 과정에서 알게된 점들을 적어두려합니다🙄
# super minimal flask app
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
아래는 Flask document(2.0.x)에 명시된 프로젝트 구조입니다. 이번 과제는 해당 도큐먼트를 참조하여 진행했습니다.
flaskr/
a Python package containing your application code and files.tests/
a directory containing test modules.venv/
a Python virtual environment where Flask and other dependencies are installed.app.py
vs app/__init__.py
$ export FLASK_APP=flask
$ export FLASK_ENV=development
$ flask run
rest api
flask의 rest api 라이브러리로는 Flask-restful
, flask-restplus
, flask-restx
가 있으나, restplus
는 사실상 restx
가 fork해서 진행중이므로 Flask-restful
vs flask-restx
의 구조 인듯합니다. 가장 큰 차이점은 Swagger 지원의 유무인데, restx은 내장해 지원하는 반면 restful은 따로 라이브러리를 설치해야합니다.
추가적인 내용은 Flask REST API 문서 자동화 하기, Flasgger를 참고하면 좋을 듯 합니다.
request & response controll
redirect와 404를 리스폰스로 보낼 때 여러 선택지가 있었습니다.
Flask 모듈의 Response(302,url)
혹은 redirect(url,code=302)
400 리스폰스 또한 Response(404)
/ abort(404)
/ @app.errorhandler(404)
등.
이부분은 차후에 다시 다뤄볼 것.
CORS error
이건 로컬에서 fetch로 서버에 데이터를 요청했을 때 Cross Origin Resource Sharing (CORS)를 적용하지 않아 리스폰스를 받아오지 못해서 생겼습니다.flask_cors
모듈로 모든 도메인에 대해 적용해두었으나, 두번째 인자에 상세 설정을 명시할 수도 있습니다.
import flask_cors CORS
# 모든 도메인
CORS(app)
CORS(app, resources={r'*': {'origins': '*'}})
# 특정 도메인
CORS(app, resources={r'*': {'origins': 'https://example.com'}})
# 특정 도메인+포트+하위주소
CORS(app, resources={r'/_api/*': {'origins': 'https://example.com:5000'}})
또한 데코레이터를 통해 각각 url에 적용할 수도 있습니다.
@app.route("/")
@cross_origin()
def index():
return "index"
flask document
sqlalchemy
랜덤한 flask_secretkey 생성방법들
flask_restful 사용법
cors
cors의 올바른 해결방법
fetch cors
init.py vs run.py
400 handling