安装库并引用

pip install flask

from flask import Flask, jsonify, request, Response

编写API接口

  1. 封装成有参请求
    本接口的功能是封装一个post请求,通过form表单方式上传trancode、response内容,服务接收到把response写入到以trancode命名的文件中
log = get_log('interface.log', 'info')

# 创建一个服务,赋值给APP
app = Flask(__name__)

# 指定接口访问的路径(set_response是API名称),支持什么请求方式get,post
@app.route('/set_response', methods=['post'])
def set_response():
    trancode = request.form.get('trancode')
    response = request.form.get('response')
    
    # 根据当前文件所在位置组装模板文件路径
    current_dir = os.path.abspath(os.path.dirname(__file__))
    template_path = current_dir + '/templates/' + trancode + '.txt'
    
    # 如果路径存在则把接收到的写入到文件内
    if os.path.isfile(template_path):
        with open(template_path, 'w', encoding='utf-8') as f:
            f.truncate()
            f.write(response)
            f.close()
        log.info('要重写的文件:%s 写入成功 !' % template_path)
        return {'code': 200,'message':'sucess'}
    else:
        log.error('文件 %s 不存在,请检查!'% template_path)
        return {'code': 200, 'message': 'file not exist'}

通用日志模块介绍,可以直接使用

常用的入参方式:

form表单格式入参: request.form.get()

json 格式入参: request.json.get()

请求链接直接拼接入参: request.args.get()

2.可以封装成无参数请求

@app.route('/download/interface.log', methods=['get','post'])
def download_interfce_log():
    current_dir = os.path.abspath(os.path.dirname(__file__))
    cache_path = current_dir + '/logs/' + 'interface.log'
    with open(cache_path, encoding='UTF-8') as f:
        log_data = f.read()
        response = Response(log_data, content_type='application/octet-stream')
        return response

启动API接口服务

if __name__ == '__main__':
    ip = '127.0.0.1'
    port = 19996
    app.run(ip, port, debug=True)

使用postman调用该API

在这里插入图片描述

查看日志

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐