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

Python models.User类代码示例

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

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



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

示例1: login

def login(username=None):
    '''
    Does all the login stuff
    The whole login system is called from this
    '''
    # Check if banned first
    b = User.chkbnid(User.host())
    # cuserid(NULL));
    logger.debug("BANNED %d", b)

    if username:
        username = username.lower()

    user = User.by_username(username)
    if user:
        authenticate(user)
        return user

    # Get the user name
    user = None
    while not user:
        user = input_username(username)
        username = ''

    if user.id:
        # Password checking
        authenticate(user)
    else:
        register(user)
    cls()
    return user
开发者ID:d2emon,项目名称:abermud,代码行数:31,代码来源:login.py


示例2: members

def members(request, version, format):
    if request.method == 'GET':
        require_focus(request)

        try:
            if 'sherpa_id' in request.GET and 'medlemsnummer' in request.GET:
                user = User.get_users(include_pending=True).get(id=request.GET['sherpa_id'], memberid=request.GET['medlemsnummer'])
            elif 'sherpa_id' in request.GET:
                user = User.get_users(include_pending=True).get(id=request.GET['sherpa_id'])
            elif 'medlemsnummer' in request.GET:
                try:
                    user = User.get_or_create_inactive(memberid=request.GET['medlemsnummer'], include_pending=True)
                except (Enrollment.DoesNotExist, ValueError):
                    # No such member
                    raise User.DoesNotExist
            else:
                raise BadRequest(
                    u"You must supply either an 'sherpa_id' or 'medlemsnummer' parameter for member lookup",
                    code=error_codes.MISSING_REQUIRED_PARAMETER,
                    http_code=400
                )
            return HttpResponse(json.dumps(get_member_data(user)))
        except (User.DoesNotExist, ValueError):
            raise BadRequest(
                u"A member matching that 'sherpa_id', 'medlemsnummer', or both if both were provided, does not exist.",
                code=error_codes.RESOURCE_NOT_FOUND,
                http_code=404
            )
    else:
        raise BadRequest(
            u"Unsupported HTTP verb",
            code=error_codes.UNSUPPORTED_HTTP_VERB,
            http_code=400
        )
开发者ID:simensma,项目名称:sherpa,代码行数:34,代码来源:api.py


示例3: lookup_users_by_phone

def lookup_users_by_phone(phone_number):
    """Attempt to match the given phone number in an arbitrary format to one or more members"""
    phone_number = re.sub('\s', '', phone_number)
    if phone_number == '':
        return []

    # Perform raw query in order to use MSSQL's 'REPLACE' function to remove whitespace
    # Note that we're excluding Actors with end_code 'dublett' manually here
    actors = Actor.objects.raw(
        "select * from Actor where REPLACE(MobPh, ' ', '') = %s AND EndCd != %s;",
        [phone_number, ACTOR_ENDCODE_DUBLETT]
    )

    # Filter on personal members; we're never handling other membership types
    actors = [actor for actor in actors if actor.is_personal_member()]

    # Perform raw query in order to use MSSQL's 'REPLACE' function to remove whitespace
    # Note that we're excluding inactive Enrollments manually (like Enrollment.get_active() would have) here
    query = 'select * from %s where (("Paymethod" = %s or "Paymethod" = %s ) and ' \
            '"SubmittedDt" is null and REPLACE(Mob, \' \', \'\') = %s );' % (
                Enrollment._meta.db_table, '%s', '%s', '%s',
            )
    params = [PAYMENT_METHOD_CODES['card'], PAYMENT_METHOD_CODES['invoice'], phone_number]
    pending_actors = Enrollment.objects.raw(query, params)

    # Convert the matching actors to users
    users = [User.get_or_create_inactive(memberid=actor.memberid) for actor in actors]
    users += [User.get_or_create_inactive(memberid=actor.memberid) for actor in pending_actors]
    return users
开发者ID:Turistforeningen,项目名称:sherpa,代码行数:29,代码来源:util.py


示例4: register

def register():
    form = RegisterForm()
    if form.validate_on_submit():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        code = str(uuid.uuid4())
        user = User(
            username=form.username.data,
            password=hashed_password,
            email=form.email.data,
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            change_configuration={
                "new_email": form.email.data.lower(),
                "confirmation_code": code
                }
            )
            
        # email the user
        body_html = render_template('mail/user/register.html', user=user)
        body_text = render_template('mail/user/register.txt', user=user)
        email(user.email, "Welcome to Flaskbook", body_html, body_text)
        
        user.save()
        return redirect(url_for('home_app.home'))
    return render_template('user/register.html', form=form)
开发者ID:fromzeroedu,项目名称:flaskbook,代码行数:26,代码来源:views.py


示例5: confirm_membership_by_token

def confirm_membership_by_token(request):
    """
    Confirm the membership with only the given token as authentication. Note that the URL to this view is hardcoded in
    Focus which sends out emails/SMS with the URL and correct token.
    """
    try:
        token = request.GET['code']
        actor = Actor.objects.get(family_youth_member_accepted_token=token)
        youth_user = User.get_or_create_inactive(memberid=actor.memberid)
        context = {
            'token': token,
            'youth_user': youth_user,
        }
    except (KeyError, Actor.DoesNotExist):
        raise Http404

    if request.method == 'GET':
        return render(request, 'common/user/membership_confirmation.html', context)
    elif request.method == 'POST':
        try:
            User.confirm_membership_by_token(token)
            librato.increment('sherpa.medlemmer.familiemedlemskap.bekreft_ungdomsmedlem')
            return redirect('%s?code=%s' % (reverse('user:confirm_membership_by_token'), token))
        except:
            context['confirmation_error'] = True
            return render(request, 'common/user/membership_confirmation.html', context)
开发者ID:,项目名称:,代码行数:26,代码来源:


示例6: handle

    def handle(self, *args, **options):
        file_name = args[0]
        f = open(file_name, "rb")
        d = csv.DictReader(f)
        for row in d:
            username = row["username"]

            if User.objects.filter(username=username).exists():
                print "User %s exists." % (username)
            else:
                first_name = row.get("first_name", "")
                last_name = row.get("last_name", "")
                email = row.get("email", "")
                locality = row.get("locality", "")
                gender = row.get("gender", "")
                password = row.get("password", "")

                user = User(username=username, email=email, first_name=first_name, last_name=last_name)

                user.set_password(password)
                user.save()

                user.profile.gender = gender
                try:
                    user.profile.locality = Entity.objects.get(id=locality)
                except ObjectDoesNotExist:
                    print "user %s locality id %s does not exist" % (username, locality)
                user.profile.save()
开发者ID:hasadna,项目名称:open-shot,代码行数:28,代码来源:add_users.py


示例7: load_user

def load_user(id):
    if id is None:
        redirect('/login')
    user = User()
    user.get_by_id(id)
    if user.is_active():
        return user
    else:
        return None
开发者ID:jumpjumpbean,项目名称:Daya,代码行数:9,代码来源:views.py


示例8: create

def create(name, email, avatar, social_ids=None, social_accounts=None):
    user = User(
        name=name,
        email=email,
        avatar=avatar,
        social_ids=social_ids or [],
        social_accounts=social_accounts or []
    )
    yield user.save()
    return user
开发者ID:mastak,项目名称:daryna,代码行数:10,代码来源:auth.py


示例9: attempt_login

def attempt_login(request):
    matches = authenticate_users(request.POST['email'], request.POST['password'])

    if len(matches) == 1:
        # Exactly one match, cool, just authenticate the user
        user = authenticate(user=matches[0])
        log_user_in(request, user)
        return matches, None

    elif len(matches) > 1:
        # Multiple matches, let the caller handle this
        return matches, None

    elif len(matches) == 0:
        # Incorrect credentials. Check if this is a user from the old userpage system
        old_member = authenticate_sherpa2_user(request.POST['email'], request.POST['password'])
        if old_member is not None:
            # Actually, it is! Let's try to import them.
            if User.get_users().filter(memberid=old_member.memberid, is_inactive=False).exists():
                return matches, 'old_memberid_but_memberid_exists'

            # Check if a pending user exists. This shouldn't ever happen (a pending user is recently
            # enrolled, and an existing user will have been member for a long time).
            if User.objects.filter(memberid=old_member.memberid, is_pending=True).exists():
                # Give the same error ("user exists, you need to use your new password")
                return matches, 'old_memberid_but_memberid_exists'

            # Verify that they exist in the membersystem (this turned out to be an incorrect assumption)
            if not Actor.get_personal_members().filter(memberid=old_member.memberid).exists():
                # We're not quite sure why this can happen, so we'll just give them the invalid
                # credentials message - but this might be confusing for those who were able to log
                # in previously.
                return matches, 'invalid_credentials'

            # Create the new user
            try:
                # Check if the user's already created as inactive
                user = User.get_users().get(memberid=old_member.memberid, is_inactive=True)
                user.is_inactive = False
                user.set_password(request.POST['password'])
                user.save()
            except User.DoesNotExist:
                # New user
                user = User(identifier=old_member.memberid, memberid=old_member.memberid)
                user.set_password(request.POST['password'])
                user.save()

            # Update the email on this actor, in case it were to differ from the sherpa2 email
            user.update_personal_data({'email': request.POST['email']})

            # Import any fjelltreffen-annonser from the old system
            import_fjelltreffen_annonser(user)

            authenticate(user=user)
            log_user_in(request, user)
            return [user], None

        else:
            # No luck, just provide the error message
            return matches, 'invalid_credentials'
开发者ID:simensma,项目名称:sherpa,代码行数:60,代码来源:util.py


示例10: verify_memberid

def verify_memberid(ip_address, memberid, country_code, zipcode):
    """
    Returns a User object matching the given memberid, country code, and if
    Norwegian; also zipcode. Includes pending users by default. Raises a range
    of exceptions if the provided data is invalid or does not match any user:
    - MemberidLookupsExceeded: If the client IP address has performed more
      lookups than we allowed
    - CountryDoesNotExist: If the given country code is invalid
    - ActorIsNotPersonalMember: If the data matches an Actor in Focus who
      isn't a personal member
    - NoMatchingMemberid: If the data doesn't match any member
    """
    # Check that the memberid is correct (and retrieve the Actor-entry)
    if memberid_lookups_exceeded(ip_address):
        raise MemberidLookupsExceeded

    if not FocusCountry.objects.filter(code=country_code).exists():
        raise CountryDoesNotExist

    # Not filtering on Actor.get_personal_members() in order to raise explicit
    # exception for non-personal-membership matches; see below
    actor = Actor.objects.filter(
        memberid=memberid,
        address__country_code=country_code
    )

    # Require correct zipcode for domestic members
    if country_code == 'NO':
        actor = actor.filter(address__zipcode=zipcode)

    if actor.exists():
        actor = actor.get()

        # Check that it's a proper member object (note that we didn't filter
        # the query on Actor.get_personal_members())
        if not actor.is_personal_member():
            raise ActorIsNotPersonalMember

        return User.get_or_create_inactive(memberid=actor.memberid)

    # No matching actors, check for pending users
    enrollment = Enrollment.get_active().filter(memberid=memberid)

    # Require correct zipcode for domestic members
    if country_code == 'NO':
        enrollment = enrollment.filter(zipcode=zipcode)

    if enrollment.exists():
        return User.get_or_create_inactive(memberid=memberid)

    # No matches
    raise NoMatchingMemberid
开发者ID:Turistforeningen,项目名称:sherpa,代码行数:52,代码来源:util.py


示例11: post

 def post(self):
     context = self.get_context()
     form = context.get('form')
     
     if form.validate():
         user = User()
         form.populate_obj(user)
         user.password = str(flask_bcrypt.generate_password_hash(user.password),'utf-8')
         user.save()
         return redirect(url_for('user.login'))
     
     flash('Your request failed to pass','newAccount')
     return redirect(url_for('user.new'))
开发者ID:woosungchu,项目名称:heroku-resume,代码行数:13,代码来源:views.py


示例12: validate

 def validate(self):
     is_valid = super().validate()
     if not is_valid:
         return is_valid
     user = self.request().user
     old_pass = self.del_model_value('pass0')
     if User.check_password(old_pass, user) or User.check_otp(old_pass, user):
         self.add_model_value('id', self.m_request.user.id)
         print(self.m_values)
     else:
         is_valid = False
         self.set_error('pass0', 'Old password in wrong, not working?, try OTP')
     return is_valid
开发者ID:amitdhiman000,项目名称:MyOffers,代码行数:13,代码来源:forms.py


示例13: login

def login():
    if request.method == "POST" and "j_username" in request.form:
        name = request.form["j_username"]
        user_obj = User()
        user = user_obj.get_by_name_w_password(name)
        if user and flask_bcrypt.check_password_hash(user.password, request.form["j_password"]) and user.is_valid():
            remember = request.form.get("remember", "no") == "yes"

            if login_user(user, remember=remember) and user.type == 1:
                return redirect('/device/index')
            else:
                flash("登录失败")

    return render_template("/auth/login.html")
开发者ID:jumpjumpbean,项目名称:Daya,代码行数:14,代码来源:views.py


示例14: contact_person_search

def contact_person_search(request, forening_id):
    current_forening = Forening.objects.get(id=forening_id)
    if current_forening not in request.user.all_foreninger():
        raise PermissionDenied

    MAX_HITS = 100

    if len(request.POST['q']) < settings.ADMIN_USER_SEARCH_CHAR_LENGTH:
        raise PermissionDenied

    local_nonmember_users = User.get_users().filter(memberid__isnull=True)
    for word in request.POST['q'].split():
        local_nonmember_users = local_nonmember_users.filter(
            Q(first_name__icontains=word) |
            Q(last_name__icontains=word)
        )
    local_nonmember_users = local_nonmember_users.order_by('first_name')

    actors = Actor.get_personal_members()
    for word in request.POST['q'].split():
        actors = actors.filter(
            Q(first_name__icontains=word) |
            Q(last_name__icontains=word) |
            Q(memberid__icontains=word)
        )
    actors = actors.order_by('first_name')

    # Get (or create) the user objects for the first MAX_HITS actor-hits
    users = [
        User.get_or_create_inactive(a.memberid)
        for a in actors[:MAX_HITS]]

    # Merge with non-members
    users = sorted(
        list(users) + list(local_nonmember_users),
        key=lambda u: u.get_full_name())

    context = {
        'current_forening': current_forening,
        'users': users[:MAX_HITS],
    }
    return HttpResponse(json.dumps({
        'results': render_to_string(
            'central/admin/foreninger/contact_person_search_results.html',
            context,
            request=request,
        ),
        'max_hits_exceeded': len(users) > MAX_HITS or len(actors) > MAX_HITS
    }))
开发者ID:Turistforeningen,项目名称:sherpa,代码行数:49,代码来源:views.py


示例15: search

def search(request):
    if not request.is_ajax() or request.method != 'POST':
        return redirect('admin.users.views.index')

    if len(request.POST['q']) < settings.ADMIN_USER_SEARCH_CHAR_LENGTH:
        raise PermissionDenied

    local_users = User.get_users().filter(memberid__isnull=True)
    for word in request.POST['q'].split():
        local_users = local_users.filter(
            Q(first_name__icontains=word) |
            Q(last_name__icontains=word))
    local_users = local_users.order_by('first_name')

    actors = Actor.get_personal_members()
    for word in request.POST['q'].split():
        actors = actors.filter(
            Q(first_name__icontains=word) |
            Q(last_name__icontains=word) |
            Q(memberid__icontains=word))
    actors = actors.order_by('first_name')

    # Match expired users only on memberid
    expired_users = User.objects.all()
    for word in request.POST['q'].split():
        expired_users = expired_users.filter(memberid__icontains=word)
    expired_users = [u for u in expired_users if not Actor.get_personal_members().filter(memberid=u.memberid).exists()]

    # Pending users
    pending_enrollment = Enrollment.get_active()
    for word in request.POST['q'].split():
        pending_enrollment = pending_enrollment.filter(
            Q(first_name__icontains=word) |
            Q(last_name__icontains=word) |
            Q(memberid__icontains=word))
    pending_enrollment = pending_enrollment.order_by('first_name')

    members = User.get_users().filter(memberid__in=[a.memberid for a in actors])
    pending_users = User.get_users(include_pending=True).filter(memberid__in=[e.memberid for e in pending_enrollment])
    actors_without_user = [a for a in actors if a.memberid not in list(members.values_list('memberid', flat=True))]
    users = list(local_users) + list(members) + list(pending_users)

    context = RequestContext(request, {
        'users': users,
        'actors_without_user': actors_without_user,
        'expired_users': expired_users
    })
    return HttpResponse(render_to_string('common/admin/users/user_results.html', context))
开发者ID:simensma,项目名称:sherpa,代码行数:48,代码来源:views.py


示例16: users_remove_access

def users_remove_access(request, forening_id):
    current_forening = Forening.objects.get(id=forening_id)
    if current_forening not in request.user.all_foreninger():
        raise PermissionDenied

    # Verify that the user has admin access to the association
    cur_user_is_valid = request.user.has_perm(
        'sherpa/association/admin',
        association_id=current_forening.id,
    )
    # ... or is Sherpa admin
    if not cur_user_is_valid and not request.user.has_perm('sherpa/admin'):
        raise PermissionDenied

    other_user = User.get_users(
        include_pending=True).get(id=request.POST['user'])

    other_user.remove_perm(
        'sherpa/association/user',
        association_id=current_forening.id,
    )
    other_user.remove_perm(
        'sherpa/association/admin',
        association_id=current_forening.id,
    )

    messages.info(request, 'permission_deleted')
    cache.delete('user.%s.all_foreninger' % other_user.id)
    return redirect('admin:foreninger.users', current_forening.id)
开发者ID:Turistforeningen,项目名称:sherpa,代码行数:29,代码来源:views.py


示例17: update

 def update(self):
     print('saving ....')
     if User.update(self.model_values()):
         self.add_model_value('pass0', 'xxxxxxxxxxx')
         self.add_model_value('password', 'xxxxxxxxxxx')
         return self.result()
     return None
开发者ID:amitdhiman000,项目名称:MyOffers,代码行数:7,代码来源:forms.py


示例18: list_albums

def list_albums(request, album):
    albums = Album.objects.filter(parent=album).order_by("name")
    parents = []
    images = None
    current_album = None
    if album is not None:
        current_album = Album.objects.get(id=album)
        images = Image.objects.filter(album=album)
        parents = list_parents(current_album)

    fotokonkurranse_album = Fotokonkurranse.objects.get().album
    context = {
        "album": album,
        "albums": albums,
        "albumpath": parents,
        "current_album": current_album,
        "images": images,
        "origin": request.get_full_path(),
        "all_users": sorted(User.sherpa_users(), key=lambda u: u.get_first_name()),
        "current_navigation": "albums",
        "image_search_length": settings.IMAGE_SEARCH_LENGTH,
        "fotokonkurranse_album": fotokonkurranse_album,
        "album_download_part_count": Album.DOWNLOAD_PART_COUNT,
    }
    return render(request, "central/admin/images/list_albums.html", context)
开发者ID:Turistforeningen,项目名称:sherpa,代码行数:25,代码来源:views.py


示例19: user_post

	def user_post(self, *args):
		pagename = args[0]
		if args[0] is None:
			pagename=""

		exercise = Exercise.query().filter("url = ",pagename).get()
		submission = self.request.get('code')
		program = exercise.outside_code.format(submission)
		action = self.request.get('action')


		response = dict()
		if action == 'check':
			response = exercise.checker.checkWork(program, self.username)
			if response['passed']:
				user = User.query().filter('username = ', self.username).get()
				if user and (not exercise.key() in user.exercises_completed):
					user.exercises_completed.append(exercise.key())
					user.put()

		elif action == 'test':
			message = ''
			logging.info(self.request.get('input'))
			response = exercise.checker.submit(program, self.username, self.request.get('input'))
			
			if (response['error'] != "OK" or 
				int(response['result']) != 15 or 
				response['output'] is None):
					message = response['error_message']

			response['message'] = message

		self.write_json(response);
开发者ID:chrisuehlinger,项目名称:sg-study-c,代码行数:33,代码来源:views.py


示例20: get_queryset

    def get_queryset(self):
        # This method uses Focus and local users to compile a search result
        # containing users.

        # See the comment on the class definition of the lazy_queryset variable
        if self.lazy_queryset:
            return self.lazy_queryset

        SEARCH_MAX_HITS = 100
        search = self.request.query_params.get('search', '').strip()

        if len(search) < settings.ADMIN_USER_SEARCH_CHAR_LENGTH:
            raise PermissionDenied

        local_users = User.get_users()
        for word in search.split():
            local_users = local_users.filter(
                Q(first_name__icontains=word) |
                Q(last_name__icontains=word) |
                Q(email__icontains=word))
        local_users = local_users.order_by('first_name')[:SEARCH_MAX_HITS]

        users = sorted(list(local_users), key=lambda u: u.get_full_name(True))

        self.lazy_queryset = users
        return users
开发者ID:Turistforeningen,项目名称:sherpa,代码行数:26,代码来源:user.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python userentitymanager.UserEntityManager类代码示例发布时间:2022-05-27
下一篇:
Python user.User类代码示例发布时间: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