Python 回调函数实现异步处理

说到异步处理大家应该会联想到Ajax 处理,那我们先来说说什么是Ajax 请求。

Ajax 就相当于是模拟了一个信息发送请求,你可以在很多网站上注册的时候会发现,比如用户名输入“123”,那么它可能会提示你该用户已经存在,而给你的感觉是页面并没刷新,也就是并没有提交表单,而用户名又是存放在数据库内的,也就是说要查询用户名是否存在,就必须得发送表单的里的用户名,然后再在数据库中去查询。

而这个过程就是用了Ajax 来处理的,用户输入用户名,当表单的焦点发生变化的时候,则会触发Ajax,然后Ajax 发送一个GET或者POST请求给服务器,服务器就会处理传递过来的数据!

今天给大家分享的是在Python 里面通过回调函数来实现异步的处理。

示例代码如下所示:

import threading
import time
import datetime

#第一个请求
def request_1():
    print("the request 1 is start")
    io(callback)
    print("the request 1 is end")

#第二个请求
def request_2():
    print("the request 2 is start")
    time.sleep(2)
    print("the request 2 is end")

#获取数据请求类的操作,如:从db读取数据,循环耗时,调用其他api等
def io(callback):
    def run(call):
        print("the run is start")
        time.sleep(5)
        print("the run is end")
        conn_db=[x for x in range(10000)] #模拟从db获取数据
        call(conn_db)
    # 这里是启动一个线程去处理这个io操作,不用阻塞程序的处理
    threading.Thread(target=run,args=(callback,)).start()

#回调函数
def callback(data):
    print("the callback is start")
    print("the response of callback is:",data)
    print("the callback is end")

if __name__ == '__main__':
    start_time=datetime.datetime.now()
    request_1()
    request_2()
    end_time=datetime.datetime.now()
    #这里是在统计总耗时,从打印的结果可以看到是异步处理的。
    print("the spend of total time is:",(end_time-start_time).seconds)

输出内容如下:

the request 1 is start
the run is start
the request 1 is end
the request 2 is start
the request 2 is end
the spend of total time is: 2
the run is end
the callback is start
the response of callback is:[0, 1,...]
the callback is end

Process finished with exit code 0

总结:

异常的处理就是在我们需要等待一个io 耗时处理时,可以不用排队等待而去做其他的可以处理的事情,这样就提高了系统的处理效率,这对于一个系统来说是非常重要的。

欢迎关注【无量测试之道】公众号,回复【领取资源】,
Python编程学习资源干货、
Python+Appium框架APP的UI自动化、
Python+Selenium框架Web的UI自动化、
Python+Unittest框架API自动化、

资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:

 添加关注,让我们一起共同成长!

猜你喜欢

转载自blog.csdn.net/weixin_41754309/article/details/110198739