我想将我的flask应用程序连接到Mongodb cloud,但是当我运行它时,它在verify function的行(44,if condition)显示了一个错误,Mongodb代码在这里开始执行。
这是我的代码,它返回
pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed
from flask import Flask, render_template, request, url_for
import smtplib # for send message to mail
from random import randint # to generate random number
import re # for email validation
import pymongo # for connect with database
from pymongo import MongoClient
from flask_pymongo import PyMongo
from flask_mongoengine import MongoEngine
myclient = MongoClient("mongodb+srv://xxxxxx:Xxxxxx12@ashish-hbjy0.mongodb.net/test?retryWrites=true&w=majority")
mydb = myclient.emailverify # database name
mycol = mydb["otp"] # table name
app = Flask(__name__)
randotp = randint(1000, 9999) # Random 4 digit OTP Generator
otp = randotp
@app.route('/')
def home():
return render_template('home.html')
@app.route('/verify', methods=['POST', 'GET'])
def verify():
global email, otp
if request.method == 'POST':
info = request.form
email = request.form.get('email')
if info.get('email', None) is not None:
if email in [temp['email'] for temp in mycol.find({}, {"_id":0, "email":1})]: # at here it stuck
global msg # alreay verified message
msg = "Email Already Verified"
return render_template('status.html', result = email, message=msg)
else:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("vacancykey123@gmail.com", "@vacancyKey1")
otpmessage = "Your OTP " + str(otp)
s.sendmail("vacancykey123@gmail.com", email, otpmessage)
print("sent mail")
#mycol.insert_one({ "email": email})
print("email entered!")
s.quit()
return render_template('verify.html', result = info)
@app.route('/status', methods=['POST','GET'])
def status():
if request.method == 'POST':
sentotp = int(request.form.get('otp'))
semail = email
if sentotp == otp:
mycol.insert_one({ "email": email}) # at here it stuck
msg = "Email Verified"
return render_template('status.html', email= semail, message = msg)
else:
msg = "Wrong OTP, Please check again!"
return render_template("status.html", message = msg)
if __name__ == '__main__':
app.run()
我如何解决这个问题,我认为这基本上是mongodb云数据库与flak的连接问题
当我将它与本地主机mongodb连接时,它将成功执行。你知道吗
但是当我将它与mongodb云连接时,它会生成ServerSelectionTimeoutError
。你知道吗
我建议您部署自己的mongodb进行测试,因为您的远程数据库服务器端似乎存在一些连接问题
在本地计算机上安装mongodb
相关问题 更多 >
编程相关推荐