我正在尝试创建一种方法,允许我通过用户电子邮件查询端点。还有比我下面所做的更好的方法吗?可能只返回一条或零条记录。
@User.query_method(query_fields=('email',),
path='get_by_mail',
name='user.get_by_email')
def get_by_email(self, query):
return query
最佳答案
我假设User
是一些继承自EndpointsModel
的自定义模型。如果没有,这将会失败。换句话说,您已经做了这样的事情:
from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
class User(EndpointsModel):
email = ndb.StringProperty()
...
有两种主要方法可以解决此问题,您可以使用电子邮件
作为实体的键,或者滚动您自己的查询并尝试获取两个实体以查看您的结果是否唯一并且存在。
选项 1:使用电子邮件
作为 key
您可以执行simple get,而不是执行完整的查询。 .
from google.appengine.ext import endpoints
@endpoints.api(...)
class SomeClass(...):
@User.method(request_fields=('email',),
path='get_by_mail/{email}',
http_method='GET', name='user.get_by_email')
def get_by_email(self, user):
if not user.from_datastore:
raise endpoints.NotFoundException('User not found.')
return user
使用电子邮件作为每个实体的数据存储键,如 custom alias properties sample 中所做的那样。例如:
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
class User(EndpointsModel):
# remove email here, as it will be an alias property
...
def EmailSet(self, value):
# Validate the value any way you like
self.UpdateFromKey(ndb.Key(User, value))
@EndpointsAliasProperty(setter=IdSet, required=True)
def email(self):
if self.key is not None: return self.key.string_id()
选项 2:滚动您自己的查询
@User.method(request_fields=('email',),
path='get_by_mail/{email}',
http_method='GET', name='user.get_by_email')
def get_by_email(self, user):
query = User.query(User.email == user.email)
# We fetch 2 to make sure we have
matched_users = query.fetch(2)
if len(matched_users == 0):
raise endpoints.NotFoundException('User not found.')
elif len(matched_users == 2):
raise endpoints.BadRequestException('User not unique.')
else:
return matched_users[0]
关于python - 通过邮箱查询端点用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508970/