这段 python 代码有什么问题? if 块没有被执行
我正在编写一个模块,其中电子邮件字符串在插入数据库之前经过验证。当我尝试输入无效的电子邮件字符串时,它会打印带有错误电子邮件消息的其他块,但当我输入正确的电子邮件字符串时,它不会执行任何操作。这是代码:
#!/usr/bin/python
import MySQLdb
import re
# Open database connection
db = MySQLdb.connect("localhost","root","root","acl" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
def addUser(email,password):
try:
if validateEmail(email):
sql = "INSERT INTO acl_users(email, password) VALUES ('%s', '%s')" % (email, password)
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
else:
print "wrong email"
except Exception as inst:
# Rollback in case there is any error
db.rollback()
print inst
def validateEmail(email):
if len(email) > 7:
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
return True
else:
return False
else:
return False
请问有什么建议吗?
edit-1
得到了答案,伙计们!在 except 块中创建异常实例后,我知道 import re 丢失了。这解决了问题。
I am writing a module, in which the email string is validated before it gets inserted into the db. When i try to enter invalid email string it prints else block with wrong email message but when i enter the correct email string it doesnt do anything. Here is the code:
#!/usr/bin/python
import MySQLdb
import re
# Open database connection
db = MySQLdb.connect("localhost","root","root","acl" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
def addUser(email,password):
try:
if validateEmail(email):
sql = "INSERT INTO acl_users(email, password) VALUES ('%s', '%s')" % (email, password)
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
else:
print "wrong email"
except Exception as inst:
# Rollback in case there is any error
db.rollback()
print inst
def validateEmail(email):
if len(email) > 7:
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)quot;, email) != None:
return True
else:
return False
else:
return False
Any suggestions please?
edit-1
got the answer guys! after creating instance of the exception in except block i got to know that import re was missing. that solved the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 validateEmail 中,您使用了模块 re,但没有导入它。
in validateEmail you use the module re, but you did not import it.
我会打印出异常并查看它失败的原因。
I would print out the exception and see why it's failing.
是否有可能在 if 块中抛出异常?在 except 块中放置一条 print 语句来检查这一点。
此外,拥有一个包罗万象的 except 块通常不是一个好主意。如果您预计会出现数据库错误,则可以使用 except 块来捕获它们。
Is it possible that an exception is thrown in the if block? Put a print statement in the except block to check for that.
Also it's usually a bad idea to have a catch-all except block. If you're anticipating database errors then have a except block that catches them.