< 작업 환경 >
Flask 2.2.2
Flask-MySQLdb 1.0.1
1. flask-restx 설치
필자는 1.0.6 버전이 설치되었습니다.
# flask-restx 설치
pip3 install flask-restx
# 아래 커맨드를 통해 pip3로 설치한 패키지 확인
pip3 list
pip3 list |grep flask
# flask-restx 1.0.6
2. Swagger 세팅 진행
#### vim routes.py
# Swagger Setting
from flask_restx import Api, Resource, reqparse
api = Api(app, version='1.0', title='API 문서', description='Swagger 문서', doc="/api-docs")
http://999.888.777.666:5000/api-docs
정상적으로 Swagger web이 불러와지는지 확인합니다.
3. Test API들 만들어서 Swagger에 잘 나오는지 확인
test_api = api.namespace('test', description='API Test')
@test_api.route('/')
class Test(Resource):
def get(self):
return "api success!"
@test_api.route('/json')
class Jsontest(Resource):
def get(self):
return jsonify(test="test001")
4. GET Method API 샘플
# app/routes.py
# 이용자 정보 제공
@cross_origin()
@real_api.route('/<string:idx>/userInfo')
class userInfo(Resource):
@staticmethod
def get(idx):
try_select, data = models.user_info(idx)
if try_select:
return data, 200
else:
return data, 401
# app/models.py
def user_info(idx):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(SELECT_USERS+'WHERE idx = %s', [idx])
account = cursor.fetchone()
if account:
return True, account
else:
return False, {'result':'Not Exist User'}
5. 정보 등록하기 POST Method API 샘플
# app/routes.py
# ...
# request.form에list 애들이 모두 들어있으면 1, 아니면 완성률로 출력
def check_in_list_all(list, request_datas):
count = 0
for each in list:
if each in request_datas:
count += 1
return count/len(list)
# api post method 쓸 때 사용
def make_input_model(model_name, api, list):
fields_sample = dict()
for each in list:
fields_sample[each] = fields.String(required=True)
input_model = api.model('InputModel_'+model_name, fields_sample)
return input_model
# ...
# 교실 정보 등록
get_fields_list_classRegister = ['idx', 'class_name', 'monetary_unit', 'school_name', 'class_grade', 'class_number']
input_model_classRegister = make_input_model('classRegister', real_api, get_fields_list_classRegister)
@cross_origin()
@real_api.route('/classRegister')
class classRegister(Resource):
@real_api.expect(input_model_classRegister)
def post(self):
input_data = request.get_json()
success_rate = check_in_list_all(get_fields_list_classRegister, input_data)
if success_rate == 1:
fromip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
try_classRegister, data = models.class_register(input_data['idx'], input_data['class_name'], input_data['monetary_unit'], input_data['school_name'], input_data['class_grade'], input_data['class_number'], fromip)
if try_classRegister:
return data, 200
else:
return data, 204
else:
return {'result':'Not Correct Form'}, 404
# app/models.py
# ...
def class_register(idx, class_name, monetary_unit, school_name, class_grade, class_number, fromip):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(SELECT_USERS+'WHERE idx = %s', [idx])
account = cursor.fetchone()
if account:
if account['user_attendanceNumber'] == 0:
cursor.execute(SELECT_CLASSES+'WHERE class_name = %s', [class_name])
data = cursor.fetchone()
if data:
return False, {'result':'Already Exist Class Name'}
else:
# 클래스코드 (초대코드) 랜덤생성
class_code = randint(10000000, 99999999)
cursor.execute("INSERT INTO `classes` (`idx`, class_name, monetary_unit, school_name, class_grade, class_number, createdFromIp, class_code) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", (idx, class_name, monetary_unit, school_name, class_grade, class_number, fromip, class_code))
mysql.connection.commit()
cursor.execute(SELECT_CLASSES+'WHERE idx = %s', [idx])
data = cursor.fetchall()
return True, data
return False, {'result':'Not Allowed Type. You\'re Not Teacher.'}
else:
cursor.execute(SELECT_USERS+'WHERE idx = %s', [idx])
data = cursor.fetchone()
return False, {'result':'Not Exist User'}
# ...