python - 如何使用 Django 生成 6 位多个 OTP 并一次插入数据库
问题描述
我正在生成 6 位随机 OTP,views.py
我只想使用单个 QuerySet 一次插入那些要插入到我的表中的许多 OTP。 这是我的代码:
主页.html
<form class="" action="" method="post">
{% csrf_token %}
<div class="" style="text-align: center:">
Mobile : <input type="text" name="mobile" value="">
<input type="submit" name="submit" value="Generate OTP">
</div>
</form>
模型.py
class otpModel(models.Model):
mobile = models.CharField(max_length=30, blank=False, null=True)
otp = models.CharField(max_length=50, blank=False, null=True)
def __str__(self):
return self.mobile
视图.py
import random
from app_name.models import otpModel
def registerOTP(request):
if request.method == 'POST':
mobile = request.POST['mobile']
for i in range(100):
otp = random.randint(100000, 999999)
otp = otpModel.objects.create(mobile=mobile, otp=otp)
if otp:
messages.info(request, 'OTP is saved!!!')
return render(request, 'app_name/otp.html')
else:
return render(request, 'studentexams/otp.html')
每当我在 HTML 表单中输入手机号码时,表格中只会插入 1 个 OTP。是否有任何解决方案可以使用单个 QuerySet 一次插入多个 OTP
请给出完成此任务的代码片段
解决方案
尝试以下
from itertools import islice
def registerOTP(request):
if request.method == 'POST':
mobile = request.POST['mobile']
otps = []
for i in range(100):
otp = random.randint(100000, 999999)
otp_obj = otpModel(mobile=mobile, otp=otp)
otps.append(opt_obj)
# I advise you to do the following in a celery task
# Doing it in the request thread is a bad User experience
batch_size = 50 # 50 is the batch size, you
# can change it to any number you want based on your usecase
while True:
batch = list(islice(otps, batch_size))
if not batch:
break
otpModel.objects.bulk_create(batch, batch_size)
del otps[0:batch_size]
if otp:
messages.info(request, 'OTP is saved!!!')
return render(request, 'app_name/otp.html')
else:
return render(request, 'studentexams/otp.html')
推荐阅读
- amazon-athena - 如何跳过与 Athena 中的架构不匹配的文档?
- git - 如何解决bitbucket中的多个值的问题?
- mysql - 在 Kubernetes pod 中运行时,Mysql 访问被拒绝
- sql - 从内部连接中获取不同的行
- botframework - 如何修改 QnA 后续提示样式?
- java - FirebaseDatabase onChildChanged 返回多个快照
- reactjs - 如何自定义键盘输入和格式?
- python - PyCharm 警告 SQLAlchemy 用户模型的意外参数
- c# - 使用 .net SDK 查询 DynamoDb 表的正确方法
- excel - 如何打开一个Excel