我希望能够使用提供的电子邮件地址或用户ID(整数)从数据库中提取用户。为此,我必须检测提供的字符串是整数还是电子邮件。寻找最快的方法来做到这一点。感谢。
def __init__(self, data):
#populate class data
self._fetchInfo(data)
def _fetchInfo(self, data):
#If an email
#SELECT ... WHERE email = 'data'
#or if a user_id
#SELECT ... WHERE id = 'data'
#Fill class attributes
self._id = row['id']
self._email = row['id']
...
答案 0 :(得分:4)
在Python中处理此问题的规范方法是先尝试,稍后请求原谅:
def _fetchInfo(self, data):
try:
data=int(data)
sql='SELECT ... WHERE id = %s'
args=[data]
except ValueError:
sql='SELECT ... WHERE email = %s'
args=[data]
# This might fail, in which case, data was neither a valid integer or email address
此策略也以绰号"It is Easier to Ask for Forgiveness than Permission"为准。
答案 1 :(得分:2)
您可以使用isinstance功能:
if isinstance(data, int):
# it's an id
else:
# it's a string
虽然就个人而言,我只有两种方法,fetchById
和fetchByEmail
,以明确其工作原理。
答案 2 :(得分:2)
你说两个都是字符串,对吗?这也可行。
if data.isdigit():
# it's an id
else:
# it's not
答案 3 :(得分:1)
if '@' in data:
# email
else:
# id