Python Flask后端异步处理(三)

  前一篇博文我们已经将基础知识和环境配置进行了介绍:https://www.cnblogs.com/Cl0ud/p/13192925.html,本篇博文在实际应用场景中使用Celery,对Flask后端进行异步处理。

  首先编写一个celerytask.py文件进行Celery的配置,同时耗时任务也写在该文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from celery import Celery
from init import app
from SZheConsole import SZheScan
 
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
 
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
 
 
@celery.task
def SZheConsole(urls):
    try:
        for url in urls:
            print("="*20)
            print(url)
            SZheScan(url)
    except Exception as e:
        print("错误")
        print(e)
        pass
    print("allend!")

使用@celery.task装饰器修饰耗时函数SZheConsole,让Celery能够正确调用。

SZheScan函数是另外一个文件里面的函数,即对每一个URL进行单独的扫描,这部分过几天为了提高扫描速度会进行优化,这里将Celery用到项目里,暂时不改。

调用耗时任务SZheConsole的地方在index.py视图函数中,只选调用部分代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@app.route('/console', methods=['GET', 'POST'])
@login_required
def console():
    bugbit, bugtype = core.GetBit()
    counts = core.GetCounts()
    ports = core.GetPort()
    services = core.GetServices()
    target = core.GetTargetCount()
    try:
        lastscantime = BaseInfo.query.order_by(BaseInfo.id.desc()).first().date
    except:
        lastscantime = "暂无扫描"
        pass
    if request.method == 'GET':
        return render_template('console.html', bugbit=bugbit, bugtype=bugtype, counts=counts, lastscantime=lastscantime,
                               ports=ports, services=services, target=target)
    else:
        urls = request.form.get('urls')
        urls = urls.split()
        print(urls)
        for url in urls:
            redispool.hincrby('targetscan', 'waitcount', 1)
        # executor.submit(SZheConsole, urls)
        SZheConsole.delay(urls)
        target = core.GetTargetCount()
        return render_template('console.html', bugbit=bugbit, bugtype=bugtype, counts=counts, lastscantime=lastscantime,
                               ports=ports, services=services, target=target)
 

可以看到原来的处理方式是多进程处理

1
executor.submit(SZheConsole, urls)

将原来的处理方式代码注释掉后,关键代码修改为

1
SZheConsole.delay(urls)

这样就可以将耗时任务丢给Celery进行处理,页面立即返回

1
return render_template('console.html', bugbit=bugbit, bugtype=bugtype, counts=counts, lastscantime=lastscantime,ports=ports, services=services, target=target)

接着启动redis和Celery服务,启动redis自不用说,Celery启动命令为:

celery worker -A celerytask.celery -l INFO

(可以看出-A参数celery与文件名的关系

运行后的部分截图为:

bug1.png

接着启动Flask服务,在任务控制台输入需要扫描的网址:

bug2.png

新建任务后查看Celery的日志信息,可以看到运行成功,同时与使用原生线程/进程一样,浏览器立即返回,异步处理成功。

bug3.png

后面的博客将学习使用Celery中更流行的用法,也是原生线程/进程很难做到的部分,如显示进度条,暂停删除任务,显示后台任务状态等。

既然使用了Celery就应当把它的威力发挥到最大,以上

且听下回 咕咕咕

参考链接:


__EOF__

本文作者春告鳥
本文链接https://www.cnblogs.com/Cl0ud/p/13193704.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   春告鳥  阅读(860)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示