flask异步操作_Python Flask后端异步处理(三)
前一篇博文我們已經將基礎知識和環境配置進行了介紹:
首先編寫一個celerytask.py文件進行Celery的配置,同時耗時任務也寫在該文件中
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視圖函數中,只選調用部分代碼
@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)
可以看到原來的處理方式是多進程處理
executor.submit(SZheConsole, urls)
將原來的處理方式代碼注釋掉后,關鍵代碼修改為
SZheConsole.delay(urls)
這樣就可以將耗時任務丟給Celery進行處理,頁面立即返回
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與文件名的關系
運行后的部分截圖為:
接著啟動Flask服務,在任務控制臺輸入需要掃描的網址:
新建任務后查看Celery的日志信息,可以看到運行成功,同時與使用原生線程/進程一樣,瀏覽器立即返回,異步處理成功。
后面的博客將學習使用Celery中更流行的用法,也是原生線程/進程很難做到的部分,如顯示進度條,暫停刪除任務,顯示后臺任務狀態等。
既然使用了Celery就應當把它的威力發揮到最大,以上
且聽下回 咕咕咕
參考鏈接:
總結
以上是生活随笔為你收集整理的flask异步操作_Python Flask后端异步处理(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql启动后在哪里编程_启动mysq
- 下一篇: 钢琴调音一般收费是多少钱一次