小记如何用Flask实现一个带POST的api。
# -*- coding: utf-8 -*-
import json
from flask import Flask, request, Response
from logging import FileHandler, INFO, Formatter
app = Flask(__name__)
# log
err_log = FileHandler('error_log_'+time.strftime('%Y%m%d',time.localtime()))
err_log.setLevel(INFO) #设置日志级别
logging_format = Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') # 日志格式
err_log.setFormatter(logging_format)
app.logger.addHandler(err_log)
@app.route('/',methods=['POST','GET']) #'/'指定了路径
def CERTAIN_FUNCTION():
if request.method == 'POST':
... #POST过来的数据可用request.form[]将其解析出来,如果是json的话可用request.json获取
return Response(json.dumps(xxxx), mimetype='application/json') # 如果需要回传json的话
# return xxx 当然也可直接回传字符串或某个方法
if __name__ == '__main__':
app.run(host='x.x.x.x',port='xxxx')
Reference: