当前位置: 首页>>代码示例>>Python>>正文


Python User.get_by_key_name方法代码示例

本文整理汇总了Python中models.User.get_by_key_name方法的典型用法代码示例。如果您正苦于以下问题:Python User.get_by_key_name方法的具体用法?Python User.get_by_key_name怎么用?Python User.get_by_key_name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.User的用法示例。


在下文中一共展示了User.get_by_key_name方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
    def get(self, boker_id):

        boker = Boker.get_by_id(int(boker_id))
        if boker:
            deferred.defer(update_num_view, str(boker.key()))

            # Check post type, Video or Photo
            if boker.video_id and boker.video_source:
                self.template = 'video.html'
                if self.current_user is not None:
                    user = User.get_by_key_name(self.current_user['id'])
                    can_like = not Like.already_like(user, boker)
                else:
                    can_like = False
            else:
                active_contest = Contest.active_contest()
                if active_contest:
                    is_nominee = Contest.is_nominee(boker)

                if self.current_user is not None:
                    user = User.get_by_key_name(self.current_user['id'])
                    can_vote = not Vote.already_vote(user)
                    can_like = not Like.already_like(user, boker)
                else:
                    can_vote = False
                    can_like = False
                    
                querystring = self.request.GET

            return self.render_response(self.template, locals())
        else:
            self.abort(404)
开发者ID:ekaputra07,项目名称:bokerface,代码行数:34,代码来源:site.py

示例2: current_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
 def current_user(self):
     try:
         """Returns the active user, or None if the user has not logged in."""
         if not hasattr(self, "_current_user"):
             self._current_user = None
             cookie = facebook.get_user_from_cookie(
                 self.request.cookies, self.get_config('facebook', 'app_id'), self.get_config('facebook', 'app_secret'))
             if cookie:
                 # Store a local instance of the user data so we don't need
                 # a round-trip to Facebook on every request
                 user = User.get_by_key_name(cookie["uid"])
                 if not user:
                     graph = facebook.GraphAPI(cookie["access_token"])
                     profile = graph.get_object("me")
                     user = User(key_name=str(profile["id"]),
                                 id=str(profile["id"]),
                                 name=profile["name"],
                                 email=profile["email"],
                                 profile_url=profile["link"],
                                 access_token=cookie["access_token"])
                     user.put()
                     try:
                       name =  user.name.split()
                       fname = name[0]
                       lname = name[len(name)-1]
                       deferred.defer(export_email_mailchimp,{'email':user.email,"fname":fname,"lname":lname})
                     except:
                       pass
                 elif user.access_token != cookie["access_token"]:
                     user.access_token = cookie["access_token"]
                     user.put()
                 self._current_user = user
         return self._current_user
     except:
         self._current_user = None
开发者ID:seedprod,项目名称:pagify,代码行数:37,代码来源:handlers.py

示例3: get

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
  def get(self):
    user = self.current_user
    if user:
      userprefs = get_userprefs(user["id"])
    else:
      self.redirect('/')
      return
    
    search_latlng = (userprefs.search_lat,userprefs.search_lng)

    friends_local_not_user_uid_list = list()
    friends_with_locals_list = list()
    friends_local_2 = dict()
    
    graph = facebook.GraphAPI(version=2.1,access_token=user["access_token"])

    friends = get_friends(graph)
    friends[:] = [friend for friend in friends if is_app_user(str(friend['id']))]
    friends_local = [friend for friend in friends if is_local(str(friend['id']),search_latlng)]
    
    for profile in friends:
      user_2 = User.get_by_key_name(str(profile['id']))
      if user_2.offline_token_created + timedelta(2*365/12) < datetime.utcnow():
        logging.info('Friend ' + str(profile['id']) + ' access token expired') 
        continue
      graph_2 = facebook.GraphAPI(version=2.1,access_token=user_2.offline_token)

      friends_2 = get_friends(graph_2)
      friends_2[:] = [friend for friend in friends_2 if is_app_user(str(friend['id']))]
      friends_2_local = [friend for friend in friends_2 if is_local(str(friend['id']),search_latlng)]
    
      for profile_2 in friends_2_local:
        # ignore mutual friend
        # FIXME inefficient, assumes 1st degree list is shorter than 2nd, use sets?
        if any(f['id'] == profile_2['id'] for f in friends):
          continue
        # ignore "me"
        if str(profile_2['id']) == str(user['id']):
          continue
        if profile_2['id'] in friends_local_2:
          friends_local_2[profile_2['id']]['friends'].append(profile)
        else:
          profile_2['friends'] = list()
          profile_2['friends'].append(profile)
          friends_local_2[profile_2['id']] = profile_2

    template = template_env.get_template('friends.html')
    context = {
      'facebook_app_id': FACEBOOK_APP_ID,
      'facebook_app_namespace': FACEBOOK_APP_NAMESPACE,
      'user': user,
      'userprefs': userprefs,
      'location_name': search_latlng,
      'location_link': "https://friendsbylocation.appspot.com/",
      'friends_local': friends_local,
      'friends_local_2': friends_local_2,
      'friends_local_not_user_uid_list': friends_local_not_user_uid_list,
      'friends_with_locals_list': friends_with_locals_list,
    }
    self.response.out.write(template.render(context))
开发者ID:lucasrangit,项目名称:FriendsByLocation,代码行数:62,代码来源:main.py

示例4: before_request

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
def before_request():
    """
    adds facebook configuration data to g.
    if the session includes a user_key it will also try to fetch
    the user's object from memcache (or the datastore).
    if this succeeds, the user object is also added to g.
    """
    g.facebook_application_id = app.config['FACEBOOK_APPLICATION_ID']

    if 'user_key' in session:
        user = cache.get(session['user_key'])

        if user is None:
            # if the user is not available in memcache we fetch
            # it from the datastore
            user = User.get_by_key_name(session['user_key'])

            if user:
                # add the user object to memcache so we
                # don't need to hit the datastore next time
                cache.set(session['user_key'], user)

        g.user = user
    else:
        g.user = None
开发者ID:allanberger,项目名称:deck-flask-gae,代码行数:27,代码来源:main.py

示例5: current_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
 def current_user(self):
     if self.session.get("user"):
         return self.session.get("user")
     else:
         cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                FACEBOOK_APP_ID,
                                                FACEBOOK_APP_SECRET)
         
         if cookie:
             user = User.get_by_key_name(cookie["uid"])
             if not user:
                 graph = facebook.GraphAPI(cookie["access_token"])
                 profile = graph.get_object("me")
                 user = User(
                     key_name = str(profile["id"]),
                     id = str(profile["id"]),
                     name = profile["name"],
                     profile_url = profile["link"],
                     access_token = cookie["access_token"]
                 )
                 user.put()
             elif user.access_token != cookie["access_token"]:
                 user.access_token = cookie["access_token"]
                 user.put()
         
             self.session["user"] = dict(
                 name = user.name,
                 profile_url = user.profile_url,
                 id = user.id,
                 access_token = user.access_token
             )
             return self.session.get("user")
     return None
开发者ID:alarkirikal,项目名称:veebivalimised,代码行数:35,代码来源:valimised.py

示例6: current_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
    def current_user(self):
        """
        :returns object: User object or None
        """
        if not hasattr(self, "_current_user"):
            logging.info("not hasattr")
            self._current_user = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies,
                self.app.config.get("FACEBOOK_APP_ID", ""),
                self.app.config.get("FACEBOOK_APP_SECRET", ""))
            logging.info(str(self.request.cookies))
            if cookie:
                logging.info("if cookie")
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                user = User.get_by_key_name(cookie["uid"])
                if not user:
                    logging.info("if not user")
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    user = User(key_name=str(profile["id"]),
                                id=str(profile["id"]),
                                name=profile["name"],
                                profile_url=profile["link"],
                                access_token=cookie["access_token"])
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    logging.info("elif user.access_token")
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user = user
#             else:
#                 return None
        return self._current_user
开发者ID:sdsdsxcxc,项目名称:facebook-showposts,代码行数:37,代码来源:handlers.py

示例7: current_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
	def current_user(self):
		if not hasattr(self, "_current_user"):
			self._current_user = None
			cookie = facebook.get_user_from_cookie(
				self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
			if cookie:
				# Store a local instance of the user data so we don't need
				# a round-trip to Facebook on every request
				user = User.get_by_key_name(cookie["uid"])
				if not user:
					graph = facebook.GraphAPI(cookie["access_token"])
					profile = graph.get_object("me")
					# Change the user type's key to be a unique key (maybe openid)
					user = User(key_name=str(profile["id"]),
					#user = User(key_name=str(api.users.get_current_user().email()),
								guser=api.users.get_current_user(),
								fbid=str(profile["id"]),
								name=profile["name"],
								profile_url=profile["link"],
								access_token=cookie["access_token"])
					user.put()
				elif user.access_token != cookie["access_token"]:
					user.access_token = cookie["access_token"]
					user.put()
				self._current_user = user
		return self._current_user
开发者ID:cegme,项目名称:likeindex,代码行数:28,代码来源:example.py

示例8: post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
    def post(self):

        kwargs = {}

        username = self.request.get('username')
        password = self.request.get('password')

        kwargs['username'] = username

        user = User.get_by_key_name(username)
        if user:
            h = user.password_hash_salt
            if not hashing.valid_pw(username, password, h):
                kwargs['password_error'] = "Invalid Password"
        else:
            kwargs['username_error'] = "Invalid Username"

        error_dict = {'username_error', 'password_error'}
        if error_dict & set(kwargs.keys()) != set():
            self.render("login.html", **kwargs)
        else:
            # create cookie using hashed id
            hashed_cookie = hashing.make_secure_val(username)
            self.response.headers.add_header('Set-Cookie',
                                             'username={}; '
                                             'Path=/'.format(hashed_cookie))
            self.redirect("/welcome")
开发者ID:racheltho,项目名称:wiki,代码行数:29,代码来源:main.py

示例9: get

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
    def get(self):
        verification_code = self.request.get('verification_code')
        id = self.request.get('id')

        # fetch user from database
        user = User.get_by_key_name(id)

        # below should not happen
        if not user:
            logging.warning("Invalid User, this must not happen in Verify Handler")
            self.redirect('/logout')
            return

        #user has already been verified, so redirect him to elections page
        if user.email_verified:
            self.redirect('/vote')
        else:
            logging.info("Verifying user's Verification code")
            if user.verification_code == verification_code:
                user.email_verified = True
                user.put()
                self.redirect('/logout')
            else:
                self.render("email_form.html", error_msg="Your Verification Code is wrong. Please enter your email again.")
        return None
开发者ID:tharunreddy,项目名称:elections-app,代码行数:27,代码来源:main.py

示例10: get

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
 def get(self):
     user_id = self.request.cookies.get('user_id')
     logging.info('[SearchHandler:GET] user_id: [%s]' % user_id)
     if user_id is None or len(user_id) == 0:
         self.redirect("/")
         return
     q = self.request.get('q')
     p = self.request.get('p')
     logging.info('[SearchHandler:GET] q: [%s] p:[%s]' % (q, p))
     user = User.get_by_key_name(user_id,parent=None)
     posts = search(user, q, p)
     results = []
     for post in posts:
         if post:
             ids = post.id.split('_')
             result ={}
             result['from_name'] = post.from_name
             result['created_time'] = post.created_time
             result['date_time'] = datetime.datetime.strptime(post.created_time, '%Y-%m-%dT%H:%M:%S+0000')
             result['message'] = post.message
             result['url'] = 'http://www.facebook.com/'+ids[0]+'/posts/' + ids[1]
             results.append(result)
     template_values = {
         'user':user,
         'logout_url':settings.LOGOUT_URL,
         'results': results,
         'query': q,
         'phrase':p
     }
     template = jinja_environment.get_template('templates/search.html')
     self.response.out.write(template.render(template_values))
开发者ID:hideki,项目名称:locateweb,代码行数:33,代码来源:views.py

示例11: CheckUser

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
def CheckUser(user_data):
    user = memcache.get(u"user-%s" % user_data["id"])
    if user is None:
        user = User.get_by_key_name(u"<%s>" % user_data["id"])
        if not user:
            # python sulund on "read only"
            pointer_to_user = {'user': None}
            def tnx(user_data):
                user = User(key_name = u"<%s>" % user_data["id"])
                user.id = user_data["id"]
                user.email = user_data["email"]
                user.realname = user_data["realname"]
                user.locale = user_data["locale"]
                user.country = user_data["country"]
                user.phone = user_data["phone"]
                user.put()
                pointer_to_user["user"] = user
            try:
                db.run_in_transaction(tnx, user_data = user_data)
                memcache.set(u"user-%s" % user_data["id"], user)
                return pointer_to_user["user"]
            except db.TransactionFailedError, e:
                return False
        memcache.set(u"user-%s" % user_data["id"], user)
        return user
开发者ID:andris9,项目名称:VoteSMS,代码行数:27,代码来源:main.py

示例12: GetUser

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
def GetUser(id):
    user = memcache.get(u"user-%s" % id)
    if user is None:
        user = User.get_by_key_name(u"<%s>" % id)
        if not user:
            return False
        memcache.set(u"user-%s" % id, user)
    return user
开发者ID:andris9,项目名称:VoteSMS,代码行数:10,代码来源:main.py

示例13: checkUser

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
 def checkUser(self):
     user = User.get_by_key_name(self.user.nickname())
     if not user:
         logging.info("Creating user with key_name: {}".format(self.user.nickname()))
         newUser = User(key_name=self.user.nickname())
         newUser.put()
     else:
         logging.info("User \"{}\" logged in".format(user.key().name()))
         return True
开发者ID:ErikBjare,项目名称:AlgoBitWeb,代码行数:11,代码来源:handlers.py

示例14: user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
 def user(self):
     """A user is considered to be logged in via Twitter if they have their
     user_id stored in a secure cookie."""
     if not hasattr(self, '_user'):
         user_id = self.get_secure_cookie('user_id')
         self._user = User.get_by_key_name(user_id) if user_id else None
         if user_id and not self._user:
             logging.warn('User %s missing from datastore' % user_id)
     return self._user
开发者ID:mccutchen,项目名称:tweetlocker,代码行数:11,代码来源:handlers.py

示例15: clear_users_played_tracks

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_key_name [as 别名]
def clear_users_played_tracks(username):
    username = username.lower()
    user = User.get_by_key_name(username)
    users_played_tracks = PlayedTrack.all().ancestor(user)
    tracks_count = users_played_tracks.count()
    db.delete(users_played_tracks)
    reset_user_download_stats(user, 0, 0)

    logger.info('Deleted %s Tracks for %s' % (tracks_count, username))
    return "OK"
开发者ID:Kingside,项目名称:last-fm-dashboard,代码行数:12,代码来源:users.py


注:本文中的models.User.get_by_key_name方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。