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


Python User.get_by_id方法代码示例

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


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

示例1: post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
 def post(self):
     body = json.loads(self.request.body)
     user_id = body['user_id']
     if not user_id or not User.get_by_id(user_id):
         return self.redirect('/')
     user = User.get_by_id(user_id)
     stream_ids = body['stream_ids']
     user.subscribed_ids = [sub for sub in user.subscribed_ids
                            if sub.id() not in stream_ids]
     user.put()
开发者ID:ee382,项目名称:connexus,代码行数:12,代码来源:connexus.py

示例2: question

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def question(request, qid, **kwargs):

    session_data = {}
    if local.request.session['uid']:
        session_data['user_name'] = User.get_by_id(local.request.session['uid'])[0].name
    try:
        question = Question.get_by_id(qid)[0]
    except TypeError:
        return not_found(request)

    question.views += 1
    question.update()

    edit = question.latest_edit()[0]
    category = Category.get_by_id(question.category_id)[0]
    user = User.get_by_id(question.user_id)[0]
    
    question_data =  {
        'title' : str(edit.title),
        'category' : str(category.name),
        'votes' : str(question.votes),
        'author' : str(user.name),
        'author_id' : str(user.id),
        'avatar' : str(user.avatar),
        'views' : str(question.views),
        'created' : str(question.created),
        'body' : str(edit.body),
        }
    
    try:
        answers_list = Answer.get(where=('question_id', qid), order=('votes', 'desc'))
        answer_data_list = []
        for answer in answers_list:
            answer_user = User.get_by_id(answer.user_id)[0]
            answer_edit = AnswerEdit.get(where=('answer_id', answer.id))[0]
            answer_data = {
                'votes' : str(answer.votes),
                'author' : str(answer_user.name),
                'author_id' : str(answer_user.id),
                'avatar' : str(answer_user.avatar),
                'body' : str(answer_edit.body),
                }
            answer_data_list.append(answer_data)
            
    except TypeError:
        answer_data_list = False
    
    page = Page(session_data)
    page.title = str(edit.title) + ' - Meno'
    content = Thread(question_data, answer_data_list)
    local.request.session['last'] = request.base_url
    return respond(page.render(content))
开发者ID:lachlanmarks,项目名称:meno,代码行数:54,代码来源:views.py

示例3: delete_post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def delete_post(slug):
    #post = Post.all().filter('slug =', slug).get()
    post = Post.query(Post.slug == slug).get()
    if not post:
        abort(404)
    user = g.user
    #check if it's the users post or if the user has admin?
    if User.get_by_id(int(user.key().id())) == post.author or User.get_by_id(int(user.key().id())).role == ROLE_ADMIN:
        post.delete()
        flash('Post deleted!', 'success')
        return redirect(url_for('index'))
    else:
        flash('You do not have permission to delete this post.', 'error')
    return redirect(url_for('get_post', slug=slug))
开发者ID:ardinor,项目名称:mojibake-gae,代码行数:16,代码来源:views.py

示例4: subscribe

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def subscribe():
    """
    Subscribe user from App.
    :return: confirmation
        {"code": 0, "data": {"message": "User subscribed successful!", "user_id": user_id}}
    :rtype: JSON
    :raise MethodNotAllowed: if method is neither POST neither GET
    :raise InternalServerError: if user is already subscribed
    """
    if request.method == 'POST':

        json_data = request.get_json()  # Get JSON from POST
        logging.info("From post: ")
        logging.info(json_data)

        if json_data is None:
            raise BadRequest

        user_id = json_data['userId']  # Get user_id

        try:
            private_key = json_data['privateKey']
        except Exception:
            private_key = None
            logging.info('privateKey not found')

        user = User(email=user_id)  # Create user

        if user.is_subscribed():
            user = modelUser.get_by_id(user_id)
            if private_key != None:
                user.gcm_key = private_key
                user.put()
            return jsonify(code=1, data={"userId": user_id, "message": "User already subscribed"},
                           tvType=user.tv_type, repeatChoice=user.repeat_choice,
                           enableNotification=user.enable_notification, timeNotification=user.time_notification)
        else:
            logging.info("subrscribing user")
            user.subscribe(name=json_data['userName'], birth_year=json_data['userBirthYear'],
                           gender=json_data['userGender'], gcm_key=json_data['privateKey'])

            user = modelUser.get_by_id(user_id)

            return jsonify(code=0, data={"userId": user_id, "message": "User subscribed successful!"},
                           repeatChoice=user.repeat_choice, tvType=user.tv_type,
                           enableNotification=user.enable_notification, timeNotification=user.time_notification)
    else:
        raise MethodNotAllowed
开发者ID:PRIMETIME4U,项目名称:PRIMETIME4U-server,代码行数:50,代码来源:api.py

示例5: watched_page

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def watched_page(user_id, page):
    """
    Endpoint that allow to list all watched movies listed by pages, the FIRST PAGE is 0. It uses pagination.
    :param user_id: email of the user
    :type user_id: string
    :param page: page to send
    :type page: integer
    :return: list of watched movies by page
        {"code": 0, "data": {"movies": [{"id_IMDB": id,"original_title": original_title, "poster": poster_url,
        "date": date}],"user_id": user_id, "prevPage": prevPage, "nextPage": nextPage}
    :rtype: JSON
    :raise MethodNotAllowed: if method is not GET
    :raise InternalServerError: if user is not subscribed
    :raise BadRequest: if type is neither artist neither movie
    :raise InternalServerError: if there is an error from MYAPIFILMS
    """
    user = modelUser.get_by_id(user_id)  # Get user

    if user is not None:
        if request.method == 'GET':
            return get_watched_movies_list(user, int(page))  # Return tastes
        else:
            raise MethodNotAllowed
    else:
        raise InternalServerError(user_id + ' is not subscribed')
开发者ID:PRIMETIME4U,项目名称:PRIMETIME4U-server,代码行数:27,代码来源:api.py

示例6: authorize

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def authorize():
    error = request.args.get('error')
    code = request.args.get('code')
    state = request.args.get('state')
    #TODO: Handle state here
    if error:
        flash(error, 'error')
        #TODO: Handle error here
        return redirect(url_for('home'))
    if not code:
        #TODO: No code received, something went wrong
        return redirect(url_for('home'))
    else:
        reddit = get_reddit()
        access_info = reddit.get_access_information(code)
        praw_user = reddit.get_me()
        user = User.get_by_id(praw_user.name)
        if not user:
            user = User(
                id=praw_user.name,
                username=praw_user.name,
                created_reddit=datetime.fromtimestamp(praw_user.created)
                )
        user.access_token = access_info['access_token']
        user.refresh_token = access_info['refresh_token']
        user.put()
        session['user'] = user.username
        return redirect(url_for('home'))
开发者ID:arunanm,项目名称:daily3,代码行数:30,代码来源:views.py

示例7: get

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
    def get(self):
        user = User.get_by_id(users.get_current_user().user_id())
        urlsafe_key = self.request.get('page')

        try:
            logging.info('Get page by urlsafe %s' % urlsafe_key)

            key = ndb.Key(urlsafe=urlsafe_key)
            page = key.get()
        except:
            logging.error('Error generating Page object from key.id().')
            page = None

        if page:
            if page.user == user.key:
                template_args = {
                    'page': page,
                }

                self.render_template('dashboard.html', **template_args)
            else:
                # Return 401 Unauthorized
                self.response.set_status(401)
                self.response.out.write('Unauthorized')
        else:
            # Return 404 Not Found
            self.response.set_status(404)
            self.response.out.write('Not Found')
开发者ID:josemontesdeoca,项目名称:web-monitor,代码行数:30,代码来源:handlers.py

示例8: post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
    def post(self):
        if self.user:
            self.redirect(self.uri_for('www-dashboard-admin'))
            return

        if self.request.get('email') and self.request.get('password'):
            email = self.request.get('email').strip().lower()
            password = self.request.get('password')
            user = User.get_by_id(self.request.get("email"))
            
            if not user:
                self.redirect(self.uri_for('www-login', error="User not found. Please try another email or register."))
                return
            if user.password == hash_password(email, password):
                self.login(user)
                if self.request.get('goto'):
                    self.redirect(self.request.get('goto'))
                else:
                    self.redirect(self.uri_for('www-dashboard-admin'))
                return
            else:
                self.redirect(self.uri_for('www-login', error="Wrong password. Please try again.", email=email))
                return
        else:
            self.redirect(self.uri_for('www-login', error="Please enter your email and password."))
开发者ID:kramix888,项目名称:clearfix,代码行数:27,代码来源:main.py

示例9: get

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
 def get(self):
     user_id = self.get_secure_cookie("token", "")
     user = User.get_by_id(user_id)
     if user:
         self.finish({"device_id": user['device']})
     else:
         raise HTTPAPIError(401)
开发者ID:cnspica,项目名称:Joyaay,代码行数:9,代码来源:user.py

示例10: finish_process

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def finish_process(request, user, last_updated):
    user_entity = User.get_by_id(user, namespace=DS_VERSION)
    bu_entity = BusyUser.get_by_id(user, namespace=DS_VERSION)

    # possible as same tasks may be executed more than once, see
    # https://developers.google.com/appengine/docs/python/taskqueue/overview-push#Python_Using_push_queues
    if bu_entity is None:
        logging.warning("Processing %s who wasn't registered as BusyUser", user)
    else:
        bu_entity.worker_count -= 1
        if bu_entity.worker_count == 0:
            user_entity.last_updated = last_updated
            user_entity.put()

            # do the shoutin'
            if bu_entity.shout:
                msg = ('Your tag visualizations are ready at %s/history?user=%s'
                        ' and %s/tag_graph?tp=20&user=%s'
                        % (request.host_url, urllib.quote(user),
                            request.host_url, urllib.quote(user)))

                try:
                    shout_resp = lfm_api.user_shout(user, msg)
                    if 'status' in shout_resp and shout_resp['status'] == 'ok':
                        logging.info('Shouted to ' + user)
                    else:
                        logging.error('Error shouting to %s: %s',
                            user, shout_resp)
                except lastfm.InvalidSessionError:
                    logging.error('Could not shout. Last.fm session invalid.')

            bu_entity.key.delete()

        else:
            bu_entity.put()
开发者ID:newgiin,项目名称:genrehistory,代码行数:37,代码来源:tagworker.py

示例11: POST

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
    def POST(self):
        data = web.data()
        data = json.loads(data)
        username = data.get("username")
        password = data.get("password")
        password_repeat = data.get("password_repeat")

        if password != password_repeat:
            return bad_request('两次密码输入不一致')

        user_data = {
            "username": username,
            "password": sha1(password),
            "registed_time": datetime.now(),
        }

        try:
            user_id = User.create(**user_data)
        except sqlite3.IntegrityError:
            return bad_request('用户名已存在!')

        user = User.get_by_id(user_id)
        session.login = True
        session.user = user

        result = {
            'id': user_id,
            'username': username,
        }
        return json.dumps(result)
开发者ID:fatfan,项目名称:mychat,代码行数:32,代码来源:handlers.py

示例12: resetpwd

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def resetpwd(token=''):
    msg = None
    form = ResetPwdForm()
    if token != '':
            form.token.data = token

    if not form.token.data:
        return redirect(url_for('index.home'))

    token_str = str(form.token.data)
    user = None
    try:
        data = EncryptionUtil.decrypt(token_str).split('#')
        user = User.get_by_id(data[0])
        if user.email != data[1]:
            return redirect(url_for('index.home'))
    except Exception as e:
        return redirect(url_for('index.home'))

    if form.validate_on_submit():
        if user and form.pwd.data:
            user.pwd = str(form.pwd.data)
            User.update(user)
            login_user(user)
            return redirect(url_for('index.home'))

    return render_template('account/resetpwd.html', form=form)
开发者ID:nocoffe,项目名称:pyweb,代码行数:29,代码来源:account.py

示例13: user_post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
    def user_post(self,id):
        try:
            page = int(request.args.get('page', 1))
        except ValueError:
            page = 1
        
        user = User.get_by_id(id)
        if user is None:
            flash(gettext('The user was not found'), 'error')
            return redirect(url_for('UsersView:index'))
        
        limit = 5
        posts = user.get_user_posts(page=page, limit=limit)

        pagination = Pagination(page=page, 
            per_page= limit, 
            total= user.posts.count(), 
            record_name= gettext('posts'), 
            alignment = 'right', 
            bs_version= 3)

        return render_template("admin/users/user_posts.html",
            title = gettext('User\'s Posts | %(name)s', name=user.name),
            user = user,
            posts = posts,
            pagination = pagination)
开发者ID:Tibodef,项目名称:PythonBlog,代码行数:28,代码来源:views.py

示例14: get_user_alerts

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
def get_user_alerts(sheet_alerts_dict):
    """
    Get alert data corresponding to stocks for each user.
    :param sheet_alerts_dict: Nested dict mapping ssheet id to symbol to alert data.
    :return: Nested dict mapping user id to ssheet id to symbol to alert data.
    """

    d = defaultdict(dict)

    user_keys_to_notify = {u.key for u in User.query(User.notify == True)}

    for sheet_id, symbol_alert_dict in sheet_alerts_dict.items():

        sheet = Sheet.get_by_id(sheet_id)
        if sheet is None:
            continue

        symbol_alert_dict = copy.copy(symbol_alert_dict)
        symbol_alert_dict['sheet_title'] = sheet.title

        for user_key in sheet.user_keys:
            if user_key in user_keys_to_notify:
                d[user_key.id()][sheet_id] = symbol_alert_dict

    for user_id in d:
        d[user_id]['email'] = User.get_by_id(user_id).email

    return d
开发者ID:jalexvig,项目名称:stock_tracker,代码行数:30,代码来源:db.py

示例15: get_ndb_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_by_id [as 别名]
 def get_ndb_user(self):
     """
     Get user from the datastore.
     :return user from the datastore
     :rtype models.User
     """
     return modelUser.get_by_id(self.email())
开发者ID:PRIMETIME4U,项目名称:PRIMETIME4U-server,代码行数:9,代码来源:manage_user.py


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