기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

Flask 13. pythonanywhere에 배포하기

Flask 13. pythonanywhere에 배포하기 Login: PythonAnywhere It's always a pleasure to hear from you! Ask us a question, or tell us what you love or hate about PythonAnywhere. We'll get back to you over email ASAP. Sorry, there was an error connecting to the server. Please try again in a few moments... www.pythonanywhere.com from http://ohdowon064.tistory.com/124 by ccl(A) rewrite - 2020-03-11 15:54:10

[ubuntu] FLASK_APP

[ubuntu] FLASK_APP Development/Debugging 🐞 FLASK_ENV=development FLASK_APP = app.py flask run zsh: command not found: FLASK_APP ✔️ FLASK_ENV=development FLASK_APP=app.py flask run 띄어쓰기를 해서 저런 오류를 출력할수도 있구나 😲 참고 : 108p에서 FLASK가 FKAS로 오타나있다. from http://hee-stories.tistory.com/18 by ccl(A) rewrite - 2020-03-24 17:20:11