python-54-异步处理demo记录

一、异步处理

记录近期在写flask时,遇到的一个linux小坑,顺便写个小demo。

gevent 库,异步处理小demo,注意异步调用的函数入参,需要在函数内完成程序处理。

gevent.spawn(函数, 参数1, 参数2)

from gevent import monkey;monkey.patch_all()
from flask import Flask, request, jsonify
import time, gevent, requests

app = Flask(__name__)


def send_txt(txt, key=None, sleep=60):
    time.sleep(sleep)
    key = key if key else 'xxxxx-08fd-4656-9a58-06077exxx'
    url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}'
    rq_body = {
        "msgtype": "text",
        "text": {
            "content": f'{txt}'
        }
    }
    res_carry = requests.post(url, json=rq_body)
    if 'ok' in res_carry.text:
        print(f'推送通知群:【成功】 | {rq_body} | 企业微信响应:{res_carry.text}')
    else:
        print(f'推送通知群:【失败】 | {rq_body} | 企业微信响应:{res_carry.text}')
    return res_carry.json()


@app.route('/callback', methods=['GET'])
def yxx_callback():
    txt = request.args.get('txt')
    if not txt:
        txt = '异步处理发送消息推送:默认值'
    # 异步处理发送消息推送
    gevent.spawn(send_txt, txt)
    return jsonify({'callback': 1, 'result': 'ok'})


if __name__ == '__main__':
    port = 5001
    app.debug = True
    app.run(
        host='0.0.0.0',
        port=port
    )

另外linux yum安装python3,使用 gevent 库可能会出现这个问题:

error: command 'gcc' failed with exit status 1

需要运行命令解决:yum python3-devel -y

posted @ 2022-04-10 21:46  广深-小龙  阅读(36)  评论(0编辑  收藏  举报