• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.User类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test

def test(loop):
    logging.error('1111111')
    yield from orm.create_pool(loop=loop,user='pyblog_data',password='pyblog_data',db='pyblog')
    logging.error('2222222')
    u=User(name='Test',email='[email protected]',passwd='1234567890',image='blank')
    logging.error('333333')
    yield from u.save()
开发者ID:yesbuter,项目名称:PyBlog,代码行数:7,代码来源:ormtest.py


示例2: get_user_ranking

 def get_user_ranking(self, request):
     """Inefficient way to find ranking, for the user request
     find the user and then compare win ratio with other users
     if win ratio is equal, compare the number of losses"""
     user = User.query(User.name == request.user_name).get()
     if not user:
         raise endpoints.NotFoundException(
             'A User with the name {} does not exist!'.format(request.user_name))
     users = User.query(User.name != request.user_name)
     losses = user.losses
     wins = user.wins
     win_ratio = user.win_ratio
     ranking = 0
     total_users = 1
     for other_user in users:
         total_users = total_users + 1
         if other_user.win_ratio < win_ratio:
             ranking = ranking - 1
         elif other_user.win_ratio == win_ratio:
             if other_user.losses >= losses:
                 ranking = ranking - 1
     ranking = total_users + ranking
     #Create a ranking message
     msg = "User {} Ranking {} Win Ratio {}".format(user.name, ranking, win_ratio)
     return StringMessage(message = msg)
开发者ID:abhiuee,项目名称:Project4_udacity,代码行数:25,代码来源:api.py


示例3: after_login

def after_login(resp):
    if resp.email is None or resp.email == "":
        flash('Invalid login. Please try again.')
        redirect(url_for('login'))
    user = User.query.filter_by(email = resp.email).first()
    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        nickname = User.make_unique_nickname(nickname)
        user = User(nickname = nickname, email = resp.email, role = ROLE_USER)
        models.session.add(user)
        models.session.commit()
        models.session.add(user.follow(user))
        models.session.commit()
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember = remember_me)
    return redirect(request.args.get('next') or url_for('demo'))
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember = remember_me)
    return redirect(request.args.get('next') or url_for('demo'))
开发者ID:bessiec,项目名称:SNAPBasket,代码行数:27,代码来源:views.py


示例4: add_user

def add_user():
    mobile = request.form.get('mobile')
    username = request.form.get('username')
    password = request.form.get('password')
    u = User({'mobile': mobile, 'username': username,
              'password': password})
    u.upsert()
    i = 0
    lnames = []
    while True:
        login_name = request.form.get('accounts[{}][login_name]'.format(i))
        login_password = request.form.get(
            'accounts[{}][login_password]'.format(i))
        if login_name and login_password:
            a = Account({'user_id': u._id,
                         'login_name': login_name,
                         'login_password': login_password})
            a.upsert()
            lnames.append(login_name)
            i += 1
        else:
            break
    Account.delete_many({'user_id': u._id,
                         'login_name': {'$nin': lnames}})
    return jsonify(status=200)
开发者ID:sopnic,项目名称:ybk,代码行数:25,代码来源:app.py


示例5: api_get_users

def api_get_users():
    total = User.count_all()
    page = Page(total, _get_page_index())
    users = User.find_by("order by created_at desc limit ?,?", page.offset, page.limit)
    for u in users:
        u.password = "******"
    return dict(users=users, page=page)
开发者ID:skyoskiyqq,项目名称:JnswWebApp,代码行数:7,代码来源:urls.py


示例6: session_from_facebook

def session_from_facebook():
    """
    uses the facebook session cookie to create a site specific session.

    it will also fetch profile information from facebook and add
    the user to the datastore if it does not exist yet
    """
    import facebook
    # get facebook user id and token from facebook cookie
    fb_user = facebook.get_user_from_cookie(request.cookies,
                                            app.config['FACEBOOK_APPLICATION_ID'],
                                            app.config['FACEBOOK_APPLICATION_SECRET'])

    if fb_user:
        # check whether the user is already in the datastoreg
        user = User.all().filter('facebook_id =', str(fb_user['uid'])).get()

        if user is None:
            # if not we fetch his profile information via the facebook graph api
            graph = facebook.GraphAPI(fb_user["access_token"])
            profile = graph.get_object("me")

            # now we can put the user in the datastore
            user = User(key_name=generate_key(),
                        facebook_id=str(profile['id']),
                        facebook_token=request.values.get('access_token'),
                        email=profile['email'],
                        name=profile['name'])
            user.save()

        # last but not least we add the user's key to the session cookie
        session['user_key'] = user.key().name()
    return "ok"
开发者ID:allanberger,项目名称:deck-flask-gae,代码行数:33,代码来源:main.py


示例7: __call__

 def __call__(self, form, field):
     try:
         User.get(User.email == field.data)
     except Exception:
         pass
     else:
         raise ValidationError('User with this email already exists')
开发者ID:bequ1ck,项目名称:tornado-redis-angular-chat,代码行数:7,代码来源:forms.py


示例8: chat

def chat():

	# Require login
	if 'username' not in session:
		return redirect('/login/')

	# Get chat buddy
	name_them = request.args.get('user', None)
	user_them = None
	if name_them:
		try:
			user_them = User.get(User.username == name_them)
		except:
			pass

	# Bad user - add error
	if not user_them:
		if name_them:
			errors = ["Could not find user %s." % name_them]
		else:
			errors = ["Please specify a user to chat with."]
		return render_template('chat.html', data={'errors': errors});

	# Chat avatars
	user_you = User.get(User.username == session['username'])

	return render_template('chat.html', data={'yourPic': user_you.imageUrl, 'theirPic': user_you.imageUrl, 'otherUsername': name_them, 'myLanguage': user_you.language })
开发者ID:ace-n,项目名称:wildhacks-fa14,代码行数:27,代码来源:main.py


示例9: get

    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,代码行数:32,代码来源:site.py


示例10: add_interests

def add_interests(user_id, interests):
    logger.warning('add_interests user_id:%s interests:%s' % (user_id, str(interests)))
    user = User.get_by_id(user_id)
    for interest in interests:
        if not interest:
            continue
        if interest not in user.get('interests', []):
            User.push_user_field(user_id, 'interests', interest)
        network = user.get('network')
        interest = interest.strip('#').lower()
        interest_data = Interest.get_by_name_network(interest, network)
        int_col = get_interest_collection()
        
        if not interest_data:
            #Add a new one
            interest_data = {
                'name'          : interest,
                'num_followers' : 1,
                'followers'     : [user_id],
                'network'       : network,
                'created'       : datetime.datetime.now(),
                'creator'       : user_id
            }
            user_id = int_col.insert(interest_data)
        else:
            #Update existing
#            push={}
#            updates = {}
            followers = interest_data.get('followers')
            if user_id not in followers:
                updates = {"$push" : {'followers' : user_id}, "$set" : { "num_followers" : len(followers) + 1 }}
                int_col.update({"name" : interest}, updates)
开发者ID:pchennz,项目名称:KEEN-full,代码行数:32,代码来源:tasks.py


示例11: create_new_user_activation

def create_new_user_activation(user_id):
    """
    Called when a new user is added to system, sets up activation and emails link to user
    Not part of tasks.new_user as that's notification based and will probably be refactored into a separate file soon
    """
    logger.warning('Starting user activation process for %s' % str(user_id))
    user = User.objects.get(_id = user_id)
    random_phrase = activation_phrases[randint(0, len(activation_phrases)-1)]
    #Generate random user activation hash
    activation_hash = User.create_activation_hash(user._id, randint(0,1000))
    User.set_user_field(user_id, 'activation_hash', activation_hash)
    
    if user.email in settings.SKIP_VALIDATION_ADDRESSES:
        user.activated = True
        User.set_user_field(user_id, 'activated', True)
        return "Email validation skipped for %s" % user._id
        
    url = 'http://keen.to/activate-%s-%s' % (random_phrase, activation_hash)
    name = user.first_name
    if not name:
        name = user.name
    logger.warning('Sending email to %s' % str(user_id))
    send_activation(name, user.email, url)
    logger.warning('Email sent to %s' % str(user_id))
    return "Email sent to %s" % user._id
开发者ID:pchennz,项目名称:KEEN-full,代码行数:25,代码来源:tasks.py


示例12: after_login

def after_login(resp):
    if resp.email is None or resp.email == "":
        flash('Invalid login. Please try again.')

        return redirect(url_for('login'))

    user = User.query.filter_by(email=resp.email).first()

    if user is None:
        nickname = resp.nickname

        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        nickname = User.make_unique_nickname(nickname)

        user = User(nickname=nickname, email=resp.email, role=ROLE_USER)
        db.session.add(user)
        db.session.commit()
        # make the user follow him/herself
        db.session.add(user.follow(user))
        db.session.commit()

    remember_me = False

    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)

    login_user(user, remember=remember_me)

    return redirect(url_for('user', nickname=user.nickname))
开发者ID:frimmy,项目名称:microblog,代码行数:31,代码来源:views.py


示例13: sign_up

def sign_up():
    _name = request.form['inputName']
    _user_name = request.form['inputUserName']
    _password = request.form['inputPassword']

    username_list = g.sql_session.query(User.username).all()
    if (_user_name,) not in username_list:
        user = User()
        user.name = _name
        user.username = _user_name
        user.password = generate_password_hash(_password)
        user.type = 1

        g.sql_session.add(user)

        try:
            g.sql_session.commit()
        except Exception as e:
            flash(str(e))
            g.sql_session.rollback()
            return redirect(url_for('.show_sign_up'))

        session['user'] = _user_name
        session['name'] = _name
        session['type'] = user.type
        return redirect(url_for('.user_home'))

    else:
        flash("The duplicated username")
        return redirect(url_for('.show_sign_up'))
开发者ID:ysrotciv,项目名称:dailytask,代码行数:30,代码来源:route.py


示例14: new_user

def new_user():
    u = User()
    u.from_json(request.json)
    print request.json
    db.session.add(u)
    db.session.commit()
    return jsonify({})
开发者ID:oaprograms,项目名称:oaflask,代码行数:7,代码来源:api.py


示例15: after_login

def after_login(resp):
    if resp.identity_url is None or resp.identity_url == "":
        flash(_('Invalid login. Please try again'))
        return redirect(url_for('login'))
    user = User.query.filter_by(identity_url = resp.identity_url).first()
    if user is None:
        nickname = resp.nickname
        email = resp.email
        if nickname is None or nickname == "":
            if email is None or email == "":
                nickname = resp.identity_url.strip("/").split("/")[-1]
            else:
                nickname = resp.email.split('@')[0]

        nickname = User.make_unique_nickname(nickname)

        user = User(identity_url = resp.identity_url, nickname = nickname, email = resp.email, role = ROLE_USER)
        db.session.add(user)
        db.session.commit()
        # make the user follow him/herself
        db.session.add(user.follow(user))
        db.session.commit()
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember = remember_me)
    return redirect(request.args.get('next') or url_for('index'))
开发者ID:recfab,项目名称:learn-flask,代码行数:28,代码来源:views.py


示例16: test_delete

 def test_delete(self):
     self.create_data(4, table=1)
     assert User.at(1).delete().execute() == 1
     assert User.where(
         (User.name == 'name1') | (User.name == 'name2')
     ).delete().execute() == 1
     assert User.count() == 2
开发者ID:zhangjinglei,项目名称:skylark,代码行数:7,代码来源:tests.py


示例17: welcoming_task

def welcoming_task(message):
    chat_id = message.chat.id

    new_members_names = []
    new_members_info = []
    users = []

    for member in message.new_chat_members:
        new_members_names.append(member.first_name)
        new_members_info.append(user_info(member))
        if not member.is_bot:
            user = {
                'user_id'   : member.id,
                'chat_id'   : chat_id,
                'first_name': member.first_name,
                'last_name' : member.last_name,
                'is_member' : True
            }
            users.append(user)

    if users:  # Bot check
        with db.atomic():
            User.insert_many(users).on_conflict_replace().execute()

    if str(message.chat.id) == config.mm_chat:
        welcoming_msg = "{}, {}!\nЕсли здесь впервые, то ознакомься с правилами — /rules, " \
                        "и представься, если несложно.".format(random.choice(config.welcome_list),
                                                               ', '.join(new_members_names))
    else:
        welcoming_msg = "{}, {}!\n".format(random.choice(config.welcome_list), ', '.join(new_members_names))
    my_bot.reply_to(message, welcoming_msg)
    action_log("User(s) {} joined the chat.".format(', '.join(new_members_info)))
开发者ID:arvego,项目名称:mm-randbot,代码行数:32,代码来源:mm-randbot.py


示例18: test_limit

 def test_limit(self):
     self.create_data(10)
     query = User.limit(4).select()
     results = query.execute()
     assert results.count == 4
     assert len(tuple(User.limit(9, offset=1).getall())) is 9
     assert len(tuple(User.limit(100, offset=9).getall())) is 1
开发者ID:zhangjinglei,项目名称:skylark,代码行数:7,代码来源:tests.py


示例19: api_register_user

async def api_register_user(*, email, name, passwd):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('password')

    users = await User.findAll('email=?', [email])
    if len(users) > 0:
        raise APIError('register failed', 'email', 'Email is already in use')

    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    passwd = hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest()
    image = 'http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(
        email.encode('utf-8')).hexdigest()
    user = User(uid=uid,
                name=name.strip(),
                email=email,
                passwd=passwd,
                image=image)
    await user.save()
    # make session in cookie
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(user, 86400),
                 max_age=86400,
                 httponly=True)
    user.passwd = '********'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
开发者ID:chensource,项目名称:BeginningPython,代码行数:33,代码来源:handlers.py


示例20: login

def login():

    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))
    form_l = LoginForm()
    form_s = SignUpForm()

    if form_l.validate_on_submit() and (len(form_l.openid.data) < 100) and (len(form_l.password.data) < 100):
        session['remember_me'] = form_l.remember_me.data
        user = db.session.query(User).filter(User.email == form_l.openid.data).filter(User.password == md5(form_l.password.data).hexdigest()).first()
        if user is not None:
            login_user(user, remember = form_l.remember_me.data)
            return redirect(url_for('index')) 
        else: 
            print("NOT FOUND")
        
    if form_s.validate_on_submit() and (len(form_s.email.data) < 100) and (len(form_s.login.data) < 50) and (len(form_s.password.data) < 100):
        k = False
        user = db.session.query(User).filter(User.email == form_s.email.data  or  User.nickname == form_s.login.data).first()
        if user is None:
            u = User(nickname=form_s.login.data, email=form_s.email.data, password=md5(form_s.password.data).hexdigest())
            db.session.add(u)
            db.session.commit()
            db.session.add(u.follow(u))
            db.session.commit()
            login_user(u)
            return redirect(url_for('index')) 
        else:
            print("EXISTS")
             
    return render_template('login1.html',
        form_l = form_l,
        form_s = form_s)
开发者ID:charepushko,项目名称:microblogging,代码行数:33,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.UserData类代码示例发布时间:2022-05-27
下一篇:
Python models.Url类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap