Flask 异步任务处理记录

在flask中,可能遇到长时间执行的任务,而前端需要快速响应请求,目前解决方案较好的是新开线程执行耗时任务,先将返回请求结果给前端。

接口调函数:

from flask import Blueprint
from flask import Flask, request, jsonify
app = Flask(__name__)
easyhome = Blueprint('easyhome', __name__, template_folder='easyhome')

@easyhome.route('/easyhome/vehicle_routine_calc', methods=['GET'])
def apistart():
    import threading
    # 线程调用耗时任务
    t1 = threading.Thread(target=long_workers)
    t1.start()
    t1.join(5)
    return jsonify({"code": 200, "msg": "success", "res": "请求成功"}), 200
def long_workers():
    print("长任务")
    import time
    time.sleep(5)

接口调接口:

在某些场景下,可能会遇到接口调用接口的情况,这种情况下处理稍有变化。

from flask import Blueprint
from flask import Flask, request, jsonify
app = Flask(__name__)
easyhome = Blueprint('test', __name__, template_folder='test')

@easyhome.route('/test/call1', methods=['GET'])
def apistart():
    import threading
    request_ip = request.remote_addr if request else "128.0.0.1"  # 获取客户端IP
    request_method = request.method if request else "GET"
    request_url = request.url if request else "vehicle_routine_call"
    request_data = {'request_ip': request_ip, 'request_method': request_method, 'request_url': request_url}
    t1 = threading.Thread(target=long_workers, args=("test", request_data,))
    t1.start()
    t1.join(5)
    return jsonify({"code": 200, "msg": "success", "res": "请求成功"}), 200

@easyhome.route('/test/call2/<string:waveNo>', methods=['POST', 'GET'])
def api(x, request_data=None):
    import time
    time.sleep(10)
    print("长时间任务")
    import inspect
    stack = inspect.stack()
    if len(stack) > 2:
        caller_frame = stack[2]
        caller_name = caller_frame[3]
        if caller_name == "full_dispatch_request":
            return jsonify({"success": True, "code": 200, "message": "调用成功"})
        else:
            print(request_data['request_ip'],request_data['request_method'],request_data['request_url'] + "/" + x)
            print("200,走线程调用成功")
            print("执行结束,不必有返回")

这种情况下,由于二号接口也可能被单独执行,所以用inspect函数用来判断该接口是走线程调用还是直接调用。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容