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

Python auth.User类代码示例

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

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



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

示例1: authenticate

    def authenticate(self, username=None, password=None):

        payload = {'username': username, 'password': password}
        url = '%s/auth/login/' % (settings.API_BASE_URL,)
        r = requests.post(url, data=json.dumps(payload))

        if r.status_code == requests.codes.ok:

            token = r.headers.get('x-auth-token')
            if not token:
                return None

            try:
                user = User.objects.get(username=username)
                user.password = token
                user.save()
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username, password=token)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        elif r.status_code >= requests.codes.internal_server_error:
            raise Exception('Server error. ' + str(r.status_code))
        return None
开发者ID:KorayAgaya,项目名称:HeliosBurn,代码行数:28,代码来源:backends.py


示例2: register

def register(req):
    if req.method == 'GET':
        return render(req, 'user/register.html')
    elif req.method == 'POST':
        form = req.POST
        User.create_user(username=form['username'], password=form['password'])
        return redirect('index')
开发者ID:jungledrum,项目名称:valentine,代码行数:7,代码来源:user.py


示例3: index

def index(request):
	firstname = "";
	lastname = "";
	username = "";
	password = "";
	email = "";
	if request.method == 'GET':
		return render(request, 'myapp/signup.html', {'rangerDay':range(1,32),'rangerYear':range(2014,1905,-1),})
	elif request.method == 'POST':
		firstname = request.POST['txtFirstName']
		lastname = request.POST['txtLastName']
		username = request.POST['txtUserName']
		password = request.POST['txtPassWord']
		email= request.POST['txtEmail']
		try:
			user = User()
			user.username = username
			user.first_name = firstname
			user.last_name = lastname
			user.email = email
			user.set_password(password);
			user.save()
			
			_profile = UserProfile()
			_profile.user_id = user
			_profile.save()
			
			user.backend = 'mongoengine.django.auth.MongoEngineBackend'
			logout(request)
			login(request, user)
			return HttpResponseRedirect('/mainscreen')
		except mongoengine.errors.NotUniqueError as e:
				return getSignupError(request,'Đã tồn tại trong hệ thống',firstname,lastname,username,password,email)
开发者ID:cuongnmfis,项目名称:dms,代码行数:33,代码来源:SignUp.py


示例4: register

def register(request):
    # errors = []
    # if(request.POST.get('password','1') != request.POST.get('confirm_password','1')):
    #     errors.append('wrong_password')
    # if(request.POST.get('username', "field is empty") == "" or request.POST.get('email', "field is empty") == "" or request.POST.get('password',"field is empty") == ""):
    #     errors.append('empty_field')
    # if(len(errors) != 0):
    #     return render_to_response('profile/register.html', {'errors': errors}, RequestContext(request))
    # else:


    if request.user.is_authenticated():
         my_user = MyUser.objects.get(user=User.objects.get(id=request.user.id))
         return render_to_response('profile/profile.html', {'my_user': my_user}, RequestContext(request))
    users_from_database = User.objects.all()
    if request.POST:
        User.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password'])
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        my_user = MyUser(point=0.0,comment_count=0,disease_added_count=0,article_added_count=0,discussion_added_count=0,forum_present_count=0)
        my_user.user = user
        my_user.save()
        login(request, user)

        return render_to_response('profile/account.html',{'users': users_from_database}, RequestContext(request))
    else:
        return render_to_response('profile/register.html',{'users': users_from_database}, RequestContext(request))
开发者ID:Karolucha,项目名称:choroba,代码行数:26,代码来源:user_views.py


示例5: patientinfo

def patientinfo(request):
   message = ""
   if request.method == 'POST':
      if request.POST['requestType'] == 'newPatient':
         firstName = request.POST['firstName']
         lastName = request.POST['lastName']
         birthDate = request.POST['birthDate']
         
         if(helper.validate(birthDate)):
            username = firstName + lastName         
            userNum = len(User.objects(__raw__={'username':{'$regex': '^' + username, '$options' : 'i'}}))

            user = User.create_user(username + str(userNum), 'password')
            user.first_name = firstName
            user.last_name = lastName
            user.save()
            ion_user = IonUser(user=user, group='patient', birthdate=birthDate)
            ion_user.save()
       
            newPatient = patient(firstName=firstName, lastName=lastName, activeMeds = [], user=ion_user)
            newPatient.save()
         else:
            message = "Invalid birth date format. (should be mm-dd-yyyy)"

      if request.POST['requestType'] == 'deletePatient':
         id = request.POST['id']
         patient.objects(id=id)[0].delete()
         # don't know if we actually want to give people the ability to delete medical records...
   return render_to_response('patientinfo.html', {'Patients': patient.objects, 'message': message},
                              context_instance=RequestContext(request))
开发者ID:ludi1001,项目名称:IonMedicationSystem,代码行数:30,代码来源:views.py


示例6: setUp

 def setUp(self):
     if PY3:
         raise SkipTest('django does not have Python 3 support')
     if not DJ15:
         raise SkipTest('mongo_auth requires Django 1.5')
     connect(db='mongoenginetest')
     User.drop_collection()
     super(MongoAuthTest, self).setUp()
开发者ID:ParlantTechnology,项目名称:mongoengine,代码行数:8,代码来源:test_django.py


示例7: _fixture_setup

    def _fixture_setup(self):
        c=Category(name='Musica')
        c.save()
	c=Category(name='Restauracion')
        c.save()
	user=User.create_user('john','john')
	request = HttpRequest() 
	user=User.objects(username='john')
	self.client.login(username='john',password='john')
开发者ID:eltxabi,项目名称:proyecto,代码行数:9,代码来源:tests.py


示例8: register_page

def register_page(request):
    if request.method=='POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            User.create_user(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],email=form.cleaned_data['email'])
            return HttpResponseRedirect("/register/success")
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {'form': form})
    return render_to_response('registration/register.html',variables)
开发者ID:datawinners,项目名称:HniSpike,代码行数:10,代码来源:views.py


示例9: create_user

def create_user(user_name, password, email):
    user = User()
    try:
        # print user_name, password, email
        user.create_user(user_name, password, email)
        print "User Created!"
        new_user = User.objects.get(username=user_name)
        print "User Access Key", new_user.id
    except Exception,e:
        print "Error", e
开发者ID:Wilt,项目名称:rssi-system,代码行数:10,代码来源:create_user.py


示例10: register

def register(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        User_save = User(username=username, password=password)
        User_save.set_password(password)
        User_save.save()
        return render(request,'index.html')
    else:
        return render(request,'register.html')
开发者ID:suryamuppalla,项目名称:pyteam,代码行数:10,代码来源:views.py


示例11: register

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            User.create_user(form.cleaned_data['username'],form.cleaned_data['password1'])  
	    messages.success(request, form.cleaned_data['username'] + ' you have been successfully registered')
            return HttpResponseRedirect("/")	
    else:
        form = RegistrationForm()
    return render(request, "eventslist/register.html", {
        'form': form,
    })  
开发者ID:eltxabi,项目名称:proyecto,代码行数:12,代码来源:views.py


示例12: test_should_create_default_superuser

 def test_should_create_default_superuser(self):
     FakeCommand().handle()
     self.assertEqual(1, User.objects().count())
     user = User.objects().first()
     user_profile = UserProfile.objects().first()
     self.assertEqual('admin', user.username)
     self.assertTrue(check_password('password', user.password))
     self.assertNotEqual('password', user.password)
     self.assertEqual('[email protected]', user_profile.email)
     self.assertEqual(self.kampala, user_profile.location)
     self.assertEqual('N/A', user_profile.phone)
     self.assertEqual('Admin', user_profile.name)
     self.assertEqual('Administrator', user_profile.user.group.name)
开发者ID:unicefuganda,项目名称:necoc,代码行数:13,代码来源:test_create_super_user.py


示例13: signup

def signup(request):
    if request.method == 'POST':
        name = request.POST.get('name','')
        pw = request.POST.get('password','')
        email = request.POST.get('email','')
        
        if not verifyCaptcha(request.POST.get('g-recaptcha-response','')):
            messages.error(request, "Captcha could not be validated")
            return redirect('website:index')
        
        
        #check if either is only whitespace
        if isNoneOrEmptyOrBlankString(name) or isNoneOrEmptyOrBlankString(pw) or isNoneOrEmptyOrBlankString(email):
            return HttpResponseBadRequest('username and/or password is empty')

        if len(User.objects(username=name)) != 0:
            messages.error(request, "Username" + name + "already taken")
            return redirect('website:index')

        if len(User.objects(email=email)) != 0:
            messages.error(request, "Email" + email + "already taken")
            return redirect('website:index')

        maxLength = len("IraklisDimitriadis") #this should be a good maxLength

        if len(name) > maxLength:
            messages.error(request, "Your name is too long. Use less than "+maxLength+" letters.")
            return redirect('website:index')

        user = User.create_user(name,pw,email)
        user.save()
        UserExtension(user=user,karma=0).save()
        
       

        #log user in after registrartion
        user = authenticate(username=name,password=pw)
        if user is not None:
            if user.is_active:
                login(request, user)
                messages.success(request, 'Your account was created. Click OK to begin using Lemur.')
                return redirect('website:catalogue')

        
    elif request.method == 'GET':
        return redirect('website:index')

       

    messages.error(request, "The server let's you know, that something unexpected happened.")
    return redirect('website:index')
开发者ID:phikui,项目名称:Lemur,代码行数:51,代码来源:views.py


示例14: setup

def setup(request, template='socialregistration/setup.html',
    form_class=UserForm, extra_context=dict()):
    """
    Setup view to create a username & set email address after authentication
    """
    try:
        social_user = request.session['socialregistration_user']
        social_profile = request.session['socialregistration_profile']
    except KeyError:
        return render_to_response(
            template, dict(error=True), context_instance=RequestContext(request))

    if not GENERATE_USERNAME:
        # User can pick own username
        if not request.method == "POST":
            form = form_class(social_user, social_profile)
        else:
            form = form_class(social_user, social_profile, request.POST)
            
            if form.is_valid():
                form.save(request=request)
                user = form.profile.authenticate()
                login(request, user)

                del request.session['socialregistration_user']
                del request.session['socialregistration_profile']

                return HttpResponseRedirect(_get_next(request))

        extra_context.update(dict(form=form))

        return render_to_response(template, extra_context,
            context_instance=RequestContext(request))
        
    else:
        # Generate user and profile
        #social_user.username = str(uuid.uuid4())[:30]
        #social_user.save()

        #social_profile.user = social_user
        #social_profile.save()

        # Authenticate and login
        #user = social_profile.authenticate()
        User.create_user(user_data['username'], user_data['password'], user_data['email'])
        login(request, user)

        # Clear & Redirect
        del request.session['socialregistration_user']
        del request.session['socialregistration_profile']
        return HttpResponseRedirect(_get_next(request))
开发者ID:taras1k,项目名称:Let-eat-bee,代码行数:51,代码来源:views.py


示例15: __init__

 def __init__(self, bootstrap=False):
     self.db = settings._MONGODB
     if bootstrap:
         # load bootstrap data
         self.db.user.remove()
         User.create_user(username='[email protected]', email='[email protected]', password='[email protected]')
         self.db.menus.remove()
         self.db.menus.insert(menus)
         self.db.items.remove()
         self.db.items.insert(items)
         self.db.clients.remove()
         self.db.clients.insert(clients)
         self.db.orders.remove()
         self.db.django_session.remove()
开发者ID:diegoromero,项目名称:geekbar,代码行数:14,代码来源:mongo.py


示例16: test_should_handle_existing_profile

 def test_should_handle_existing_profile(self):
     UserProfile(phone='N/A', name='Admin', location=self.kampala, email='[email protected]').save()
     FakeCommand().handle()
     self.assertEqual(1, User.objects().count())
     user = User.objects().first()
     user_profile = UserProfile.objects().first()
     self.assertEqual('admin', user.username)
     self.assertTrue(check_password('password', user.password))
     self.assertNotEqual('password', user.password)
     self.assertEqual('[email protected]', user_profile.email)
     self.assertEqual(self.kampala, user_profile.location)
     self.assertEqual('N/A', user_profile.phone)
     self.assertEqual('Admin', user_profile.name)
     self.assertEqual('Administrator', user_profile.user.group.name)
开发者ID:unicefuganda,项目名称:necoc,代码行数:14,代码来源:test_create_super_user.py


示例17: hybrid_authentication

def hybrid_authentication(username=None,password=None):
    try:
        if email_re.search(username):
            user = User.objects(email=username).first()
        else:
            user = User.objects(username=username).first()
        if len(user) != 0:
            if password and user.check_password(password):
                    return user
            else:
                return None
        else:
            return None
    except:
        return None
开发者ID:heaven00,项目名称:The-Challenge,代码行数:15,代码来源:functions.py


示例18: index

def index(request):
	firstname = "";
	lastname = "";
	username = "";
	password = "";
	email = "";
	if request.method == 'GET':
		return render(request, 'myapp/signup.html', {'rangerDay':range(1,32),'rangerYear':range(2014,1905,-1),})
	elif request.method == 'POST':
		try:
			#parameter
			firstname = request.POST['txtFirstName']
			lastname = request.POST['txtLastName']
			username = request.POST['txtUserName']
			password = request.POST['txtPassWord']
			email= request.POST['txtEmail']
			if str(firstname).strip() == "":
				return getSignupError(request,'First name can not be empty!',firstname,lastname,username,password,email)
			elif str(lastname).strip() == "":
				return getSignupError(request,'Last name can not be empty!',firstname,lastname,username,password,email)
			elif str(username).strip() == "":
				return getSignupError(request,'User name can not be empty!',firstname,lastname,username,password,email)
			elif str(password).strip() == "":
				return getSignupError(request,'Pass word can not be empty!',firstname,lastname,username,password,email)
			elif str(email).strip() == "":
				return getSignupError(request,'Email can not be empty!',firstname,lastname,username,email)
			#insert new user
			user = User()
			user.username = username
			user.first_name = firstname
			user.last_name = lastname
			user.email = email
			user.set_password(password);
			user.save()
			user.backend = 'mongoengine.django.auth.MongoEngineBackend'
			logout(request)
			login(request, user)
			#create new profile
			_profile = UserProfile()
			_profile.user_id = request.user
			_profile.save()
			return HttpResponseRedirect('/home')
		except mongoengine.errors.ValidationError as ex:
			return getSignupError(request,str(ex.errors['email']),firstname,lastname,username,password,email)
		except mongoengine.errors.NotUniqueError as e:
			return getSignupError(request,'User has already exists!',firstname,lastname,username,password,email)
		except Exception as e:
			return getSignupError(request,str(e),firstname,lastname,username,password,email)
开发者ID:cuongnmeas,项目名称:ase,代码行数:48,代码来源:SignUp.py


示例19: clean_email

 def clean_email(self):
     email = self.cleaned_data['email']
     user = User.objects(email=email)
     if len(user) == 0:
         return email
     else: 
         raise forms.ValidationError(self.error_messages['email_exists'])
开发者ID:heaven00,项目名称:The-Challenge,代码行数:7,代码来源:forms.py


示例20: test_search_form_return_correct_event

    def test_search_form_return_correct_event(self):
        user=User.create_user('john','john')
	request = HttpRequest() 
	user=User.objects(username='john')
	self.client.login(username='john',password='john')

	response = self.client.post('/eventslist/addevent',data={'title': 'Concierto','description': 'Es un concierto','category': 'Musica','lat':'49.8','lng':'4.7'}) 
        self.assertEqual(Event.objects(title='Concierto').count(),1) 
	self.assertEqual(str(Event.objects(title='Concierto')),'[<Event: Concierto-49.84.7-Es un concierto-Musica>]')

	response = self.client.post('/',data={'title': 'Concierto','category': 'Musica','lat':'49.8','lng':'4.7','distance':'4'}) 
	
	self.assertContains(response,'<td>Concierto</td>')
	self.assertContains(response,'<td>Es un concierto</td>')
	self.assertContains(response,'<td>Musica</td>')
	User.objects(username='john').delete()
开发者ID:eltxabi,项目名称:proyecto,代码行数:16,代码来源:tests.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python shortcuts.get_document_or_404函数代码示例发布时间:2022-05-27
下一篇:
Python context_managers.switch_db函数代码示例发布时间: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