기본 콘텐츠로 건너뛰기

Flask 웹 api 기본 구성 코드

Flask 웹 api 기본 구성 코드

from flask import Flask,request,jsonify import logging from functools import wraps

app = Flask(__name__)

file_handler = logging.FileHandler('app.log') app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO)

def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth: return authenticate()

elif not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs)

return decorated

@app.route('/ntalk', methods = ['GET', 'POST']) @requires_auth def response(): # logging app.logger.info(str(request))

# get handling if request.method == 'GET': if 'code' in request.args: return "code: " + request.args['code']+"

"

# post handling elif request.method == 'POST': if request.headers['Content-Type'] == 'application/json': input_json = request.get_json() data = { 'msg' : input_json['message'], 'number' : 3 } resp = jsonify(data) resp.status_code = 200 return resp

# 404 error handling @app.errorhandler(404) def not_found(error=None): message = { 'status': 404, 'message': 'Not Found: ' + request.url, } resp = jsonify(message) resp.status_code = 404 return resp

def check_auth(username, password): return username == 'admin' and password == 'secret'

def authenticate(): message = {'message': "Authenticate."} resp = jsonify(message) resp.status_code = 401 resp.headers['WWW-Authenticate'] = 'Basic realm="Example"' return resp if __name__ == "__main__": app.run(debug = True, port = 8808, host = '0.0.0.0')

from http://perpetual.tistory.com/34 by ccl(A) rewrite - 2020-03-06 18:54:27

댓글

이 블로그의 인기 게시물

[GCP] Flask로 TF 2.0 MNIST 모델 서빙하기

[GCP] Flask로 TF 2.0 MNIST 모델 서빙하기 Google Cloud Platform 우선 TensorFlow 2.0을 설치하자. 머신에 직접 설치하거나 도커를 다운받아 사용, 혹은 구글 colab을 활용( https://www.tensorflow.org/install)하면 되는데, TensorFlow에서 권장하는대로 머신에 VirtualEnv를 활용해서 설치하자 ( https://www.tensorflow.org/install/pip). 설치하는 김에 Flask도 같이 설치해보자. Compute Machine 하나를 생성(크게 부담 없는 예제라 g1 instance)하고, SSH를 연결하여 실행하면 된다. $ sudo apt update $ sudo apt install python3-dev python3-pip $ sudo pip3 install -U virtualenv # 굳이 system-wide로 flask를 설치할 필요는 없지만 그렇게 했다. $ sudo pip3 install flask $ sudo pip3 install flask-restful # virtualenv 환경에서 tensorflow 2.0 설치 $ virtualenv --system-site-packages -p python3 ./venv $ source ./venv/bin/activate # sh, bash, ksh, or zsh (venv) $ pip install --upgrade pip (venv) $ pip install --upgrade tensorflow 모든 환경이 마련되었으니, 우선 MNIST 모델을 TF 2.0으로 Training하여 모델을 Save 해 두자(tf_mnist_train.py). 대략 99% 이상 정확도가 나온다! import tensorflow as tf import numpy as np # 학습 데이터 load ((train_data, train_label), (eval_data, eval_label)) = tf....

스프링 프레임워크(Spring Framework)란?

스프링 프레임워크(Spring Framework)란? "코드로 배우느 스프링 웹 프로젝트"책을 개인 공부 후 자료를 남기기 위한 목적이기에 내용 상에 오류가 있을 수 있습니다. '스프링 프레임워크'가 무엇인지 말 할 수 있고, 해당 프레임워크의 특징 및 장단점을 설명할 수 잇는 것을 목표로합니다. 1. 프레임워크란? 2. 스프링 프레임워크 "뼈대나 근간을 이루는 코드들의 묶음" Spring(Java의 웹 프레임워크), Django(Python의 웹 프레임워크), Flask(Python의 마이크로 웹 프레임워크), Ruby on rails(Ruby의 웹 프레임워크), .NET Framework, Node.js(Express.js 프레임워크) 등등. 프레임워 워크 종류 : 3. 개발 시간을 단축할 수 있다. 2. 일정한 품질이 보장된 결과물을 얻을 수 있다. 1. 실력이 부족한 개발자라 허다러도 반쯤 완성한 상태에서 필요한 부분을 조립하는 형태의 개발이 가능하다. 프레임워크를 사용하면 크게 다음 3가지의 장점 이 있습니다. 프레임워크 이용 한다는 의미 : 프로그램의 기본 흐름이나 구조를 정하고, 모든 팀원이 이 구조에 자신의 코드를 추가하는 방식으로 개발 한다. => 이러한 상황을 극복하기 위한 코드의 결과물이 '프레임워크' 입니다. 개발자는 각 개개인의 능력차이가 크고, 따라서 개발자 구성에 따라서 프로젝트의 결과 차이가 큽니다. 2. 스프링 프레임워크(Spring Framework) 자바 플랫폼을 위한 오픈 소스 애플리케이션 스프링의 다른 프레임워크와 가장 큰 차이점은 다른 프레임워크들의 포용 입니다. 이는 다시말해 기본 뼈대를 흔들지 않고, 여러 종류의 프레임워크를 혼용해서 사용할 수 있다는 점입니다. 대한민국 공공기관의 웹 서비스 개발 시 사용을 권장하고 있는 전자정부 표준프레임워크 이다. 여러 프레임워크들 중 자바(JAV...

Dummy to resolve the flask problems

Dummy to resolve the flask problems This post is about flask problems that I struggled with. Hope you this is useful things when you taste it. Issue : How to deploy a flask application on Apache2 Resolve : As you know, flask is a micro framework. It can be handled on Apache2 using WSGI module. See the reference. Reference: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps Issue : Flask caused ERR_CONNECTION_ABORTED on POST Resolve : There are lots issues for this problem in principle. It caused when browser keep sending some buffer but server doesn't want to receive. My case is like this (submit.html) (submit.py) @bp.route('/submit', methods=["GET", "POST"]) def submit(): return render_template("submit.html") This kinda skel code to explain this. In flask case, this can be caused when it runs as develop server such as run...