반응형
flask2

초간단 웹서버 만들기2

1편과 같은 코드를 좀 더 간단하게 줄일 수 있다.

annotation을 추가하면 좀 더 직관적으로 보기가 편하다.
사용 방법은 URL과 method를 연결할 함수 정의부 앞에 추가해 주면 된다.

다음은 간결해진 코드이다. (이번에는 로그 기능을 off하였다)

'''
test api server
'''

from flask import Flask, request
from flask_restful import Resource, Api
from flask.views import MethodView

import logging
import json,base64

import os, sys
import datetime
import threading, time

app = Flask(__name__)

# log = logging.basicConfig(filename='testsvr.log', level=logging.INFO)
# 로깅을 전부 끄기
log = logging.getLogger('werkzeug')
log.disabled = True
app.logger.disabled = True

'''
/apitest1
'''
@app.route('/apitest1', methods=['GET'])
def apitest1_get():
    data = request.args
    print('recv:', data)  # dictionary
    abc = data.get('abc')
    if abc :
        result = 'This is GET method!'+str(abc)
    else:
        result = 'Hello World! input abc'
    return result

@app.route('/apitest1', methods=['POST'])
def apitest1_post():
    # get과 동일하게 작동
    return apitest1_get()


'''
/sum
'''
@app.route('/sum', methods=['GET'])
def sum_get():
    data = request.args
    print('recv:', data)  # dictionary
    return 'Hello.'

@app.route('/sum', methods=['POST'])
def sum_post():
    logging.info('sum test')
    # print('request.data=', request.data)  # binary data read all
    data=request.get_json(force=True) # parse json string
    print('request.json=', data)
    a = data['a']
    b = data['b']
    now = datetime.datetime.now()
    print(now)
    timestr = now.strftime('%Y%m%d %H:%M:%S')
    result = {
        'sum':int(a+b),
        'time':timestr
    }
    logging.info('result='+json.dumps(result))
    return result

port = 18899
if __name__=='__main__':
    print('Start Server... port=', port)
    logging.info('start server')
    app.run(host='0.0.0.0', port=port, debug=False)
    # 디버그 모드로 하면 소스 수정시 자동으로 서버 재시작이 된다.


Written with StackEdit.

'Python' 카테고리의 다른 글

ipynb와 py 양방향 전환  (2) 2019.09.30
ipynb 노트북 파일 형상관리  (1) 2019.09.27
초간단 웹API서버만들기  (0) 2019.09.25
그래프 리셋(seaborn plot graph reset)  (0) 2019.09.20
JupyterLab에서 Python Script(.py)실행하기  (0) 2019.09.19
반응형
flask

Simple Python Web API Server

쉽고 빠르게 웹 API 서버를 만드는 방법.
언어는 Python
아래 방식을 참고하면 아주 빠르고 간단하고 쉽게 API 서버를 만들 수 있다. 여기에 서비스에 필요한 작업들을 추가만 해 주면 된다.
POST 방식으로 JSON 포맷을 사용하여 통신하는 것을 추천한다.

개발툴로 PyCharm을 사용
패키지 설치

# pip install flask
# pip install flask_restful

아래 코드를 작성한다.

  • testsvr . py
'''
test api server
'''

from flask import Flask, request
from flask_restful import Resource, Api
from flask.views import MethodView

import logging
import json,base64

import os, sys
import datetime
import threading, time

app = Flask(__name__)
api = Api(app)

log = logging.basicConfig(filename='testsvr.log', level=logging.INFO)

# 로깅을 전부 끄기
# logging.getLogger('werkzeug')
# log = logging.get
# log.disabled = True
# app.logger.disabled = True

'''
/apitest1
'''
class apitest1(MethodView):
    def get(self):
        data = request.args
        print('recv:', data)  # dictionary
        abc = data.get('abc')
        if abc :
            result = 'This is GET method!'+str(abc)
        else:
            result = 'Hello World! input abc'
        return result

    def post(self):
        # get과 동일하게 작동
        return self.get()


'''
/sum
'''
class sum(MethodView):
    def get(self):
        data = request.args
        print('recv:', data)  # dictionary
        return 'Hello.'

    def post(self):
        '''
        JSON으로 받아서 작업 후 JSON으로 결과 반환
        '''
        logging.info('sum test')
        # print('request.data=', request.data)  # binary data read all
        data=request.get_json(force=True) # parse json string
        print('request.json=', data)
        a = data['a']
        b = data['b']
        now = datetime.datetime.now()
        print(now)
        timestr = now.strftime('%Y%m%d %H:%M:%S')
        result = {
            'sum':int(a+b),
            'time':timestr
        }
        logging.info('result='+json.dumps(result))
        return result


api.add_resource(apitest1, '/apitest1')
api.add_resource(sum, '/sum')

port = 18899

if __name__=='__main__':
    print('Start Server... port=', port)
    logging.info('start server')
    app.run(host='0.0.0.0', port=port, debug=True)
    # 디버그 모드로 하면 소스 수정시 자동으로 서버 재시작이 된다.


서버 구동 스크립트는 다음을 참고

---testsvr.bat---
c:\python37\scripts\python testsvr.py

---testsvr.sh---
#!/bin/bash  
  
# [python env path...]/bin/python testsvr.py  
# linux ex)  
/opt/anaconda3/envs/tensorflow/bin/python testsvr.py  
# windows command ex)  
# c:\python37\scripts\python testsvr.py

테스트 화면 : GET 방식
주소: http://localhost:18899/apitest1?abc=123&def=456
image

테스트 화면 : POST 방식, 덧셈 API
주소: http://localhost:18899/sum
POST 데이터: {“a”:5, “b”:6}
image

Written with StackEdit.

+ Recent posts