## celery + flask 异步请求使用(一)
flask 使用 celery 进行异步请求。python 3.10 docker环境,为方便调试增加flower监控工具,查看celery运行情况
requirements.txt 文件
``` txt
amqp==5.1.1
billiard==3.6.4.0
celery==5.2.7
certifi==2022.6.15
charset-normalizer==2.1.0
click==8.1.3
click-didyoumean==0.3.0
click-plugins==1.1.1
click-repl==0.2.0
Flask==2.1.3
flower==1.1.0
humanize==4.2.3
idna==3.3
itsdangerous==2.1.2
Jinja2==3.1.2
kombu==5.2.4
MarkupSafe==2.1.1
prometheus-client==0.14.1
prompt-toolkit==3.0.30
pytz==2022.1
requests==2.28.1
six==1.16.0
tornado==6.2
urllib3==1.26.11
vine==5.0.0
wcwidth==0.2.5
Werkzeug==2.2.1
```
``` Bash
# 安装所需的依赖
pip install -r requirements.txt
```
spider.py 文件
``` python
from celery import current_app
import requests
import time
@current_app.task(soft_time_limit=10)
def run(wd):
#消耗网络资源,模拟网络延迟5秒
response = requests.get(f'http://www.baidu.com?wd={wd}')
print(response.status_code)
time.sleep(5)
return 'run celery success'
```
app.py文件
``` python
from flask import Flask
from celery import Celery
RABBITMQ_URL = f'amqp://guest:123456@172.17.0.1:5672'
def make_celery(current_app):
# 创建celery实例
current_celery = Celery(
current_app.import_name,
broker=RABBITMQ_URL
)
class ContextTask(current_celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
current_celery.Task = ContextTask
return current_celery
app = Flask(__name__)
celery = make_celery(app)
# 引入celery任务,在celery实例之后引入
from tasks.spider import run
@app.route('/', methods=['GET'])
def index():
# 调用celery任务,实现异步请求操作
run.delay('test celery')
return '<h1>Hello World!</h1>'
if __name__ == '__main__':
app.run(debug=True)
```
- 运行
``` Bash
# 运行flask,访问http://localhost:5000/
flask run -h 0.0.0.0
```
- [](https://static.adong.wiki/static/images/md/2022072401.png)
``` Bash
# 运行celery
celery -A app.celery worker -l info --uid=1
```
- [](https://static.adong.wiki/static/images/md/2022072402.png)
``` Bash
# 运行flower,访问http://localhost:5555/
celery -A app.celery flower --address=0.0.0.0 --port=5555
```
- [](https://static.adong.wiki/static/images/md/2022072403.png)
- [](https://static.adong.wiki/static/images/md/2022072404.png)
访问http://localhost:5000/ 执行异步后 , 访问http://localhost:5555 查看执行结果运行情况,也可查看打印到控制台信息
- [](https://static.adong.wiki/static/images/md/2022072405.png)