Flask 로 API 구현
2023-04-03
작년에 저는 Flask APP 을 개발하고 구축까지 하였습니다.
내용이 기억나지 않아, 짯었던 코드를 보면서 살짝 정리하고 있습니다.
아래 코드는 Flask 로 API 라우터를 구현한 부분입니다.
Flask 로 API 라우터 구현
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask_restx import Resource, Api # Api 구현을 위한 Api 객체 import | |
from flask_cors import CORS | |
# Initialize the flask class and specify the templates directory | |
app = Flask(__name__, template_folder="templates") | |
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True | |
CORS(app) | |
# Flask 객체에 Api 객체 등록 | |
api = Api(app) | |
# api 라우터 연결 | |
api.add_namespace(Hello, '/hello') | |
api.add_namespace(Todo, '/todo') | |
api.add_namespace(Naver, '/naver') | |
api.add_namespace(Stock, '/stock') | |
api.add_namespace(Learning, '/learning') | |
# html 라우터 연결 | |
app.register_blueprint(Flower) | |
# Run the Flask server | |
if(__name__=='__main__'): | |
app.run(host='0.0.0.0', port=5000) |
위에서 구현한 라우터에서 연결되어 있는 실제 로직이 들어가 있는 파일의 일부분 코드로 stock.py
에 작성을 하였습니다.
Flask 로 API 엔드포인트 구현
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask_restx import Resource, Namespace | |
Stock = Namespace('stock') | |
@Stock.route('/all') | |
class all(Resource): | |
def get(self): | |
if config.allPredictResult is None: | |
return {} | |
else : | |
return config.allPredictResult.to_json(force_ascii=False, orient='records', indent=4) |
이 두 파일이 사실상 API 의 뼈대가 되는 코드일 것이라 생각이 됩니다.
config
위 코드들 중에서 config 가 어떤 역할을 하는지 조금 이해가 안될수도 있는데,
변수저장을 위해 선언한 것으로 전역변수 쯤 된다고 보시면 됩니다.
기본 값은 전부 None 으로 되어 있으며, to_json
이라는게 보이는데, 데이터는 대부분 pandas
의 자료구조를 쓰고 있는데,
pandas
의 데이터를 json
으로 출력하기 위한 코드일 것으로 생각이 됩니다.
생각이 됩니다 라고 적은건 사실 기억이 가물가물해서 입니다.