【问题标题】:Query endpoint user by email通过邮件查询端点用户
【发布时间】:2013-03-19 19:43:17
【问题描述】:

我正在尝试制作一种方法,允许我通过用户电子邮件查询端点。有没有比我在下面做的更好的方法呢?一种可能只返回一条或零条记录。

    @User.query_method(query_fields=('email',),
                       path='get_by_mail',
                       name='user.get_by_email')
    def get_by_email(self, query):
        return query

【问题讨论】:

    标签: python google-app-engine google-cloud-endpoints endpoints-proto-datastore


    【解决方案1】:

    我假设User 是一些继承自EndpointsModel 的自定义模型。如果没有,这将失败。换句话说,你做了这样的事情:

    from google.appengine.ext import ndb
    from endpoints_proto_datastore.ndb import EndpointsModel
    
    class User(EndpointsModel):
        email = ndb.StringProperty()
        ...
    

    解决此问题有两种主要方法,您可以使用email 作为实体的键,或者滚动您自己的查询并尝试获取两个实体以查看您的结果是否唯一且是否存在。

    选项 1:使用 email 作为键

    您可以使用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]
    

    【讨论】:

    • 但稍后我可能想通过他的电话号码找到用户。我该怎么办?
    • 也许我这样做完全错了。我想制作一个由用户 google 帐户进行身份验证的 android 应用程序,然后基本上有一个端点模型,该模型具有对该用户和电话号码的引用......建议?
    • 您介意再问一个关于识别用户的最佳方法的问题吗?这里似乎完全忽略了身份验证,但是在存储用户数据时,身份验证应该是您首先要考虑的问题。
    • 一点也不。我可以向你保证,你的时间没有被浪费,我从你的回答中学到了一些东西。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    相关资源
    最近更新 更多