python - 即使输入值不同,Django 也会从 MongoDB 给出相同的响应
问题描述
我最近开始使用 Django。
我已经使用 PyMongo 模块 [pip3 install pymongo] 集成了 MongoDB。
我的问题:
即使在数据库更新后,Django 也会给我相同的数据。每当我进行一些操作时;就像将用户输入的电子邮件与数据库中现有的电子邮件 ID 进行比较一样,我每次都会得到相同的结果。
看起来结果正在被缓存。
网址.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.homepage),
path('register/', views.register),
]
视图.py
from django.shortcuts import render
from pymongo import MongoClient
from django import http
def homepage(request):
return (render(request, 'index.html'))
def register(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
client = MongoClient('mongodb://my_ip:27017/')
db = client.trainingdb
collection = db.data
emailCheck = str(collection.find({"Email":email}))
if emailCheck == "":
dbData = {
'Name': name,
'Email': email,
'Password': password
}
collection.insert_one(dbData)
return http.HttpResponse("Success!")
else:
return http.HttpResponse("Email exists in database!")
else:
return render(request, 'register.html')
该homepage
方法适用于索引页或主页。该register
方法用于注册页面。
在这里,我试图检查用户输入的电子邮件 ID 是否预先存在于数据库中。
测试用例:
第一次,我输入了一个已经在数据库中的电子邮件 ID,我得到了预期的结果:Email exists in database!
.
但是第二次,我输入了一个不在数据库中的电子邮件 ID;但我得到相同的旧结果:Email exists in database!
。
是由于缓存还是类似的原因?
解决方案
collection.find()
返回一个 Cursor 实例。出于某种原因,您将其转换为字符串并将其与""
. 但是,即使列表是空str()
的,也不会是""
,而是类似于"<pymongo.cursor.Cursor object at 0x7f10b69d0c50>"
。所以条件永远不成立。
没有理由转换为字符串或与字符串进行比较。相反,检查匹配的文档数量:
emailCheck = collection.find({"Email":email}).count()
if emailCheck == 0:
...
推荐阅读
- powershell - citrix 许可证服务器中到期日期的正确格式是什么?
- javascript - 等待元素加载然后渲染数据(vue.JS)
- openmdao - Dymos 约束对参数的依赖
- amazon-web-services - Dotnet Core AWS Lambda 用于 Cognito 确认后触发器完成
- shell - 列出所有子项目的 gradle 依赖项
- java - Docker for Windows:我们的开发设置从 3.0.0+ 版本开始停止工作
- php - PDO 返回 false 而不是空数组
- javascript - 有没有办法隐藏具有“无头:假”选项的 Puppeteer 浏览器?
- powerbi - PowerBi 创建不同年份和月份的列
- excel - 查找最近邻 Excel 算法