提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:这里可以添加本文要记录的大概内容:
使用容联云获取验证码,进行用户登录+注册,获取手机验证码使用异步,使用token。
提示:以下是本篇文章正文内容,下面案例可供参考
config.py
# 消息中间人broker设置
broker_url = 'redis://:[email protected]:6379/15' #不能写localhost
# 结果存储设置
backend_result_url = 'redis://:[email protected]:6379/16'
broker 是代理人,它负责分发任务给 worker 去执行。我使用的是 Redis 作为 broker。没有设置 CELERY_RESULT_BACKEND,默认没有配置,此时 Django 会使用默认的数据库(也是你指定的 orm 数据库)。
test_celery.py
from celery import Celery
from django.conf import settings
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day0.settings')
app = Celery('day0')
app.config_from_object('utils3.config')
app.autodiscover_tasks(settings.INSTALLED_APPS)
关于异步详细参考官方文档 链接:link
from ronglian_sms_sdk import SmsSDK
accId = '容联云通讯分配的主账号ID'
accToken = '容联云通讯分配的主账号TOKEN'
appId = '容联云通讯分配的应用ID'
def send_message():
sdk = SmsSDK(accId, accToken, appId)
tid = '容联云通讯创建的模板ID'
mobile = '手机号1,手机号2'
datas = ('变量1', '变量2')
resp = sdk.sendMessage(tid, mobile, datas)
print(resp)
在utils中创建sms_code.py文件,写入SDK
from ronglian_sms_sdk import SmsSDK
import random
import redis
from utils.test_celery import app
accId = '填写自己的ACCOUNT SID'
accToken = '填写自己的AUTH TOKEN'
appId = '填写自己的AppID'
@app.task
def send_message(mobile):
sdk = SmsSDK(accId, accToken, appId)
tid = '1'
data = random.randint(100000, 999999)
cls = redis.Redis(host='localhost', port=6379, password='123456')
cls.set('sms%s' % mobile, data, ex=300)
datas = (data, '5')
resp = sdk.sendMessage(tid, mobile, datas)
print(resp)
return resp
@app.task为异步
import jwt
from django.conf import settings
def generate_jwt(payload):
token = jwt.encode(payload=payload, key=settings.SECRET_KEY)
return token
class User(models.Model):
mobile = models.CharField(max_length=11, verbose_name='手机号码')
class Meta:
db_table = 'day0920_user'
verbose_name_plural = '手机验证码登录'
def __str__(self):
return self.mobile
from rest_framework.views import APIView
from rest_framework.response import Response
from day0920.models import User
from utils.sms_code import send_message
from utils.my_jwt import generate_jwt
import redis
class GetSMSCodeView(APIView):
def get(self, request):
mobile = request.query_params.get('mobile')
send_message(mobile)
return Response({
'code': 200,
'msg': '验证码发送成功'
})
class LoginUser(APIView):
def post(self, request):
mobile = request.data.get('mobile')
smscode = request.data.get('smscode')
if not all([mobile, smscode]): # 校验前端传来数据的完整性
return Response({
'code': 400,
'msg': '请输入账号或验证码'
})
cls = redis.Redis(host='127.0.0.1', port=6379, password='123456')
redid_data = cls.get('sms%s' % mobile) # 从redis中获取验证码
if not redid_data:
return Response({
'code': 400,
'msg': '验证码已过期'
})
if redid_data.decode('utf-8') != smscode: # 将存入redis中的验证码转码与前端数据进行比较
return Response({
'code': 400,
'msg': '验证码错误'
})
try:
# 此时数据库中有此用户,直接登录
User.objects.get(mobile=mobile)
data_ = {
'name': mobile
}
token = generate_jwt(data_)
return Response({
'code': 200,
'msg': '登陆成功',
'token': token
})
except Exception as e:
# 数据库中无此用户,进行注册登录
User.objects.create(mobile=mobile)
data_ = {
'name': mobile
}
token = generate_jwt(data_)
return Response({
'code': 201,
'msg': '登陆成功',
'token': token
})
"""day0 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('day/', include('day0920.urls'))
]
2.在app中创建接口的子路由
from django.urls import path
from .views import *
urlpatterns = [
path('get_sms_code/', GetSMSCodeViews.as_view()),
path('login_user/', LoginUser.as_view())
]
1.创建vue2项目
2.下载axios与elment-ui
3.elment-ui官方文档link
<template>
<div>
<table align="center">
<tr>
<td><h1>欢迎登陆h1>td>
tr>
<tr>
<td>
<el-input placeholder="请输入手机号" v-model="mobile">el-input>
td>
tr>
<tr>
<td>
<el-input placeholder="请输入验证码" v-model="smscode"
><el-button
style="padding-right: 10px"
slot="suffix"
type="text"
@click="getsms"
>获取验证码el-button
>el-input
>
td>
tr>
<tr>
<td><el-button @click="login">登录el-button>td>
tr>
table>
div>
template>
getsms() {
this.$axios
.get("/day/get_sms_code/", {
params: { mobile: this.mobile },
})
.then((result) => {
console.log(result);
if (result.data.code == 200) {
this.$message(result.data.msg);
}
})
.catch((err) => {
console.log(err);
});
}
login() {
this.$axios
.post("/day/login_user/", {
mobile: this.mobile,
smscode: this.smscode,
})
.then((result) => {
console.log(result);
if (result.data.code == 201 || result.data.code == 200) {
this.$message(result.data.msg);
} else if (result.data.code == 400) {
this.$message(result.data.msg);
}
})
.catch((err) => {
console.log(err);
});
}