如何通过字符串值查询NDB数据库

时间:2018-12-22 16:23:06

标签: python google-app-engine flask app-engine-ndb

我正在尝试使用flask-login创建用户登录系统,但是我在查询电子邮件地址using Google's query functions时遇到了困难。

我可以获取ID,但是由于用户登录时不会知道其ID,因此并不是很有用。

代码摘录试图做的概述(为了使概念证明有效,我对值进行了硬编码):

username = 'abc@gmail.com'
check database for username
Return true if match is found

In this guide,在9'48“处,用户编写(我假设是)sqlAlchemy查询。使用Google的NDB查询功能,该查询相当于什么?

class User(ndb.Model):
   name = ndb.StringProperty()
   email = ndb.StringProperty()
   password = ndb.StringProperty()

@login_manager.user_loader
def load_user(user_id):
return User.get_by_id(int(user_id))

@app.route('/', methods=['GET', 'POST'])
def testlogin():

#user = User.query(getattr(User, 'email') == 'abc@gmail.com')
#login_user(user)



check = 'abc@gmail.com'
query = User.query(User.email == check)
#print query
#query = User.query()
#queryuser = User.query().filter(User.email == 'abc@gmail.com')

#login_user(queryuser)
checkTable = User.get()
#checkTable.email = check
checkTable_key = checkTable
#query = checkTable_key.get()

print str(checkTable_key)

results = User.query().fetch() #this returns a list / array

#print(results)
#print "query all" + str(queryall)

#for  result in results: 
  #print "query all" + str(result.email) 


return "logged in "

1 个答案:

答案 0 :(得分:1)

check = 'abc@gmail.com'
query = User.query(User.email == check).get() # this returns the User object, or None if not found

if query:
    return True
else:
    return False

# or try
return (query != None)

# or, just return the User object?

# if you just want to see if the user exists, you should do a keys_only query, which is free:

query = User.query(User.email == check).fetch(1, keys_only=True)