03.celery发送短信接口

本文档介绍了如何使用Celery异步任务发送短信,首先在celery_task/main.py中定义了发送短信的Celery任务,然后在verifications/views.py中创建视图函数,通过Celery的delay方法异步调用发送短信。同时,添加了测试接口的详细信息,包括URL、请求参数等。
摘要由CSDN通过智能技术生成

1.使用celery异步发送短信

1.1 在celery_task/mian.py中添加发送短信函数

# celery项目中的所有导包地址, 都是以CELERY_BASE_DIR为基准设定.
# 执行celery命令时, 也需要进入CELERY_BASE_DIR目录执行.
CELERY_BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # # os.path.abspath(__file__) 作用: 获取当前脚本的完整路径
# os.path.dirname() 
print('>>>>>>',os.path.abspath(__file__)) # rusult: >>>>>> /root/shiyanlou_project/celery_task/main.py
# os.path.dirname() : 去掉一层目录 /root/shiyanlou_project/celery_task
'''
注意: 
	只有当在脚本中执行的时候,os.path.abspath(__file__)才会起作用,
	因为该命令是获取的当前执行脚本的完整路径,如果在交互模式或者terminate 终端中运行会报没有__file__这个错误
 '''



@app.task(bind=True)
def send_sms_code(self, mobile, datas):
    sys.path.insert(0, os.path.join(CELERY_BASE_DIR, '../syl'))
    # 在方法中导包
    from libs.rl_sms import send_message
    # time.sleep(5)
    try:
        # 用 res 接收发送结果, 成功是:0, 失败是:-1
        res = send_message(mobile, datas)
    except Exception as e:
        res = '-1'

    if res == '-1':
        # 如果发送结果是 -1  就重试.
        self.retry(countdown=5, max_retries=3, exc=Exception('短信发送失败'))

1.2 在verifications/views.py中添加celery发送短信试图函数

class SmsCodeView(APIView):
    """使用apiview的限流"""
    # 1. 所有人可以访问
    permission_classes = (AllowAny,)

    def post(self, request):
        # 1. 获取参数
        phone = request.data.get('phone')  # 手机号
        image_code = request.data.get('image_code')  # 图片验证码
        image_code_uuid = request.data.get('image_code_uuid')  # 前端生成的uuid

        # 2. 检查参数
        if not all([phone, image_code, image_code_uuid]):
            return Response({"code": 999, "msg": "参数不全"})
        if not re.match(r'^1[3456789]\d{9}$', phone):
            return Response({"code": 999, "msg": "手机号码不正确"})

        # 3. 检查是否发送
        redis_client = get_redis_connection('img_code')
        phone_exists = redis_client.get(phone)
        if phone_exists:
            return Response({"code": 999, "msg": "频繁发送, 请稍后再试"})

        # 验证图形验证码
        redis_image_code = redis_client.get(image_code_uuid)  # bytes
        if redis_image_code:
            # bytes 转成 string
            redis_image_code = redis_image_code.decode()

        # 比较用户提供的图片内容是否和redis中保存的一致
        if image_code.upper() != redis_image_code:
            return Response({'code': 999, 'msg': '图片验证码不正确'})

        # 4. 发送
        code = '%06d' % random.randint(0, 999999)  # 随机6位验证码

        from syl.settings import BASE_DIR
        sys.path.insert(0, os.path.join(BASE_DIR, '../celery_task'))
        from main import send_sms_code  # 必须这么写, 从main中导包

        send_sms_code.delay(phone, (code, "5"))
        print(code)

        # 5.使用 pipeline 批量操作
        pl = redis_client.pipeline()    # 实例化pipeline对象
        pl.setex(phone, 60 * 5, code)   # 存储phone:code, 5分钟有效期
        pl.delete(image_code_uuid)      # 从redis中删除这个图片验证码, 以防再次被使用
        pl.execute()

        # 6. 返回结果
        return Response({"code": 0, "msg": "短信发送成功"})

1.3 添加路由

urlpatterns = [
    path('sms_codes/', views.SmsCodeView.as_view()),
]

2.测试接口

  • 接口URL
http://192.168.56.100:8888/user/sms_codes/
  • 请求携带参数
{
    "phone": 18538x525xxx,
    "image_code":"aed3",                                         # 前端生成的 图形验证码
    "image_code_uuid":"de8edce2-fc9f-11ea-9325-005056c00008"     # 前端生成的uuid
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用 Flask 和 Celery 发送邮件的详细代码: 1. 安装所需库 ``` pip install flask flask-mail celery ``` 2. 创建 Flask 应用 ``` from flask import Flask from flask_mail import Mail app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.gmail.com' # 邮箱服务器 app.config['MAIL_PORT'] = 465 # 端口号 app.config['MAIL_USE_SSL'] = True # 是否使用 SSL app.config['MAIL_USERNAME'] = 'your-email@gmail.com' # 发送邮件的邮箱地址 app.config['MAIL_PASSWORD'] = 'your-email-password' # 发送邮件的邮箱密码 mail = Mail(app) @app.route('/') def index(): return 'Hello, World!' ``` 3. 创建 Celery 应用 ``` from celery import Celery celery = Celery(app.name, broker='redis://localhost:6379/0') celery.conf.update( CELERY_TASK_SERIALIZER='json', CELERY_ACCEPT_CONTENT=['json'], CELERY_RESULT_SERIALIZER='json' ) ``` 4. 创建邮件发送任务 ``` from flask_mail import Message from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @celery.task(name='send_email') def send_email(to, subject, body): with app.app_context(): try: msg = Message(subject=subject, recipients=[to]) msg.body = body mail.send(msg) logger.info(f"Email sent to {to} with subject '{subject}'") except Exception as e: logger.error(f"Error sending email to {to}: {e}") ``` 5. 在视图函数中调用任务 ``` @app.route('/send_email') def send_email_view(): to = 'recipient-email@example.com' subject = 'Test Email' body = 'This is a test email sent from Flask using Celery and Flask-Mail.' send_email.delay(to, subject, body) return 'Email sent!' ``` 以上就是使用 Flask 和 Celery 发送邮件的详细代码。注意,这里使用 Redis 作为 Celery 的消息代理,你需要安装并启动 Redis 服务。另外,为了保证邮件发送的安全性,建议把配置文件中的邮箱地址和密码存储在环境变量中,而不是明文写在代码中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值