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

Python sha.new函数代码示例

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

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



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

示例1: create_inactive_user

    def create_inactive_user(self, username, password, email, send_email=True):

        # Create the user.
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()
        
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation_key = sha.new(salt+new_user.username).hexdigest()
        
        # And finally create the profile.
        new_profile = self.create(user=new_user,
                                  activation_key=activation_key)
        
        if send_email:
            from django.core.mail import send_mail
            subject = "Activate your new account at %s" % settings.SITE_URL
            message_template = loader.get_template('activation_email.txt')
            message_context = Context({ 'site_url': 'http://%s' % settings.SITE_URL,
                                        'activation_key': activation_key,
                                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
            message = message_template.render(message_context)
            print settings.DEFAULT_FROM_EMAIL
            send_mail(subject, message, settings.EMAIL_HOST, [new_user.email])
        return new_user
开发者ID:kirrg001,项目名称:llib,代码行数:26,代码来源:models.py


示例2: register_application_req

def register_application_req(request):

    form = AppRegistrationForm(request.POST)
    
    if not form.is_valid():
      return render_to_response('applications/register.html',
				default_context(request, form=form))

    ip = request.META['REMOTE_ADDR']
    code = request.POST['code']
    name = request.POST['name']
    email = request.POST['email']
    url = request.POST['website_url']

    if 'save' in request.POST and request.POST['save'] == 'Save':
      id = request.POST['id']
      print "Updating ea " + id
      ea = ExternalApplication.objects.get(ea_id=id)
      ea.ea_name = name
      ea.ea_code = code
      ea.ea_contact_email = email
      ea.ea_web_site_url = url
    else:
      # Compute a random key
      key = sha.new(str(random.randint(0,1000000))+ip+code+name).hexdigest()
      secret = sha.new(str(random.randint(0,1000000))+code+ip+name).hexdigest()
      ea = ExternalApplication(ea_name=name,ea_code=code,ea_key=key,ea_ip_address=ip,ea_active_status='Pending',ea_secret=secret, ea_contact_email=email, ea_web_site_url=url)

      # add authentication token for this application
      at = AuthenticationToken(at_account_id=None,at_token=key,at_secret=secret)
      at.save()

    ea.save()
    return HttpResponseRedirect('.')
开发者ID:DraconPern,项目名称:medcommonsPhp,代码行数:34,代码来源:views.py


示例3: cadastrarUsuario

def cadastrarUsuario(request):
	dados = request.POST
	senha = dados['senha']
	senhaConfirmacao = dados['senhaconfirmacao']
	if senha == senhaConfirmacao: #Verifica se os campos senha e confirmação de senha estão preenchidos iguais
		login = dados['login']
		usuario = User.objects.get(username = login)
		print 'oi'
		if usuario is None: #caso o usuário não exista
			#Criando novo usuário inativo
			newUser = User.objects.create_user(login, login + '@cin.ufpe.br', senha)
			newUser.is_active = false
			newUser.save()
			
			#Construindo a chave de ativação para a conta
			salt = sha.new(str(random.random())).hexdigest()[:5]
			chaveAtivacao = sha.new(salt+new_user.username).hexdigest()
			dataExpiracao = datetime.datetime.today() + datetime.timedelta(2)
			
			c = RequestContext (request, {})
		elif usuario.is_active: #caso já exista um usuário com esse login e sua conta esteja ativa
			c = 'Já existe um usuário com esse login'
		else: #caso já exista um usuário com esse login mas sua conta não esteja ativa
			print 'opa' #mandar e-mail
	else:
		c = 'Você escreveu duas senhas diferentes'
	return HttpResponse(c)
开发者ID:omailson,项目名称:achadoseperdidos,代码行数:27,代码来源:views.py


示例4: validateUserAndPassword

 def validateUserAndPassword(self, username, password):
     """
     Looks first if the user is configured in the configuration file,
     e.g. standard users like the "manager" account. If not the user
     databases, like "Member", are checked. The encrypted password is
     validated.
 """
     if (username, sha.new(password).hexdigest()) not in users:
         if len(username) >= 2:
             # which database to use for user authentification
             if username[:2].lower() == "mi":
                 user = Member.search(username[2:])
             else:
                 self.warning("wrong prefix for username '%s'" % username)
                 raise LoginError, "WrongUsername"
             # check user exist and unique
             if user.count() == 0:
                 self.warning("user '%s' not found" % username)
                 raise LoginError, "WrongUsername"
             elif user.count() > 1:
                 self.warning("User '%s' not unique" % username)
                 raise LoginError, "WrongUsername"
             else:
                 # check password
                 if user[0].passwordHash == sha.new(password).hexdigest():
                     # correct user from Member database
                     self.info("User '%s' authorized" % username)
                 else:
                     self.warning("Wrong password for user '%s' in Member database" % username)
                     raise LoginError, "WrongPassword"
         else:
             self.warning("Username '%s' to short" % username)
             raise LoginError, "WrongUsername"
开发者ID:BackupTheBerlios,项目名称:esm-svn,代码行数:33,代码来源:SiteBase.py


示例5: create_inactive_user

 def create_inactive_user(self, username, password, email, send_email=True):
     """
     Creates a new User and a new RegistrationProfile for that
     User, generates an activation key, and mails it.
     
     Pass ``send_email=False`` to disable sending the email.
     
     """
     # Create the user.
     new_user = User.objects.create_user(username, email, password)
     new_user.is_active = False
     new_user.save()
     
     # Generate a salted SHA1 hash to use as a key.
     salt = sha.new(str(random.random())).hexdigest()[:5]
     activation_key = sha.new(salt+new_user.username).hexdigest()
     
     # And finally create the profile.
     new_profile = self.create(user=new_user,
                               activation_key=activation_key)
     
     if send_email:
         from django.core.mail import send_mail
         current_domain = Site.objects.get_current().domain
         subject = "Activate your new account at %s" % current_domain
         message_template = loader.get_template('registration/activation_email.txt')
         message_context = Context({ 'site_url': 'http://%s/' % current_domain,
                                     'activation_key': activation_key,
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
         message = message_template.render(message_context)
         send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
     return new_user
开发者ID:shubhamsinha92,项目名称:wseer,代码行数:32,代码来源:models.py


示例6: _verify_ftp_upload_integrity

def _verify_ftp_upload_integrity(file, file_url):
    """Download the file, and make sure that it matches the original.

    Returns True on success, and raises an Exception on failure.

    FIXME: Ideally we wouldn't have to download the whole file, we'd have
           some better way of verifying the integrity of the upload.
    """
    file.seek(0)
    old_hash = sha.new(file.read()).hexdigest()
    tries = 0

    # Try to download the file. Increase the number of retries, or the
    # timeout duration, if the server is particularly slow.
    # eg: Akamai usually takes 3-15 seconds to make an uploaded file
    #     available over HTTP.
    while tries < config.ftp_upload_integrity_retries:
        time.sleep(3)
        tries += 1
        try:
            temp_file = urllib2.urlopen(file_url)
            new_hash = sha.new(temp_file.read()).hexdigest()
            temp_file.close()

            # If the downloaded file matches, success! Otherwise, we can
            # be pretty sure that it got corrupted during FTP transfer.
            if old_hash == new_hash:
                return True
            else:
                raise FTPUploadException(
                    'Uploaded File and Downloaded File did not match')
        except urllib2.HTTPError, e:
            pass
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:33,代码来源:media.py


示例7: set_mail

def set_mail(user, email):
	if email != "":
		profile = user.get_profile()
		# Build the activation key for their account
		salt = sha.new(str(random.random())).hexdigest()[:5]
		confirmation_key = sha.new(salt+user.username).hexdigest()
		key_expires = datetime.datetime.today() + datetime.timedelta(2)



		profile.confirmation_key = confirmation_key
		profile.key_expires = key_expires
		profile.mail_confirmed = False
		profile.save()
		user.email = email
		user.save()
		# Send an email with the confirmation link

		email_subject = 'Your new hardware-fuer-alle.de email confirmation'
		email_body = """Hallo, %s, um deine E-Mail Adresse bei hardware-fuer-alle.de einzutragen musst du sie noch bestätigen\n
		Bitte klicke hierfür innerhalb der nächsten 48 Stunden auf diesen Link:\n\nhttp://hardware-fuer-alle.de/beta/accounts/confirm/%s""" % (
			user.username,
			profile.confirmation_key)
		send_mail(email_subject,
				email_body,
				'[email protected]',
				[user.email])
开发者ID:optikfluffel,项目名称:hardware-fuer-alle,代码行数:27,代码来源:views.py


示例8: register

def register(request):
	if request.POST:
		regForm = RegistrationForm(request.POST)
		
		if request.user.is_authenticated():
			return render_to_response('Accounts/register.html',{'has_account':True})
		
		new_data = request.POST.copy()
		errors = regForm.get_validation_errors(new_data)
		
		if not errors:
			# save the user
			regForm.do_html2python(new_data)
			new_user = regForm.save(new_data)
			# Build the activation key for their account  
			salt = sha.new(str(random.random())).hexdigest()[:5]
			activation_key = sha.new(salt+new_user.username).hexdigest()
			key_expires = datetime.datetime.today() + datetime.timedelta(2)
			 
			# Create and save their profile
			new_profile = UserProfile(user = new_user, activation_key = activation_key,key_expires=key_expires)
			new_profile.save 
		
	
	else:
		   regForm=RegistrationForm()
	return render_to_response('Accounts/register.html',{ 'form':regForm})
开发者ID:giftyofori,项目名称:g-project,代码行数:27,代码来源:views.py


示例9: mkpasswd

def mkpasswd(pwd,hash='ssha'):
    """Generate hashed passwords. Originated from mkpasswd in Luma
    """
    alg = {
        'ssha':'Seeded SHA-1',
        'sha':'Secure Hash Algorithm',
        'smd5':'Seeded MD5',
        'md5':'MD5',
        'crypt':'Standard unix crypt'
    }
    # Don't add support for sambapasswords unless we're using it
    if (update_sambapassword):
        alg['lmhash'] = 'Lanman hash'
        alg['nthash'] = 'NT Hash'
    if hash not in alg.keys():
        return "Algorithm <%s> not supported in this version." % hash
    else:
        salt = getsalt()
        if hash == "ssha":
            return "{SSHA}" + base64.encodestring(sha.new(str(pwd) + salt).digest() + salt)
        elif hash == "sha":
            return "{SHA}" + base64.encodestring(sha.new(str(pwd)).digest())
        elif hash == "md5":
            return "{SHA}" + base64.encodestring(md5.new(str(pwd)).digest())
        elif hash == "smd5":
            return "{SMD%}" + base64.encodestring(md5.new(str(pwd) + salt).digest() + salt)
        elif hash == "crypt":
            return "{CRYPT}" + crypt.crypt(str(pwd),getsalt(length=2))
        # nt/lm-hash are used directly in their own password-attributes.. no need to prefix the hash
        elif hash == "lmhash":
            return smbpasswd.lmhash(pwd)
        elif hash == "nthash":
            return smbpasswd.nthash(pwd)
开发者ID:tivalat,项目名称:OpenLDAP,代码行数:33,代码来源:grotan.py


示例10: create_inactive_subscription

    def create_inactive_subscription(self, instance, email_template='newsletters/opt-in.html', send_email=True, activation_key=None):
        """
        Creates a new, inactive Subscription, generates a
        Subscription and emails its activation key to the
        user. Returns the new Subscription.

        To disable the email, call with send_email=False.
        """
        if not activation_key:
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_key = sha.new(salt+instance.email).hexdigest()[:16]
        
        instance.activation_key = activation_key
        instance.subscribed = False
        instance.save()
        
        if send_email:
            from django.core.mail import send_mail
            from django.template.loader import render_to_string
            from django.contrib.sites.models import Site
            
            current_site = Site.objects.get_current()

            subject = ugettext('Confirm your subscription to %s' % (current_site.name))

            message = render_to_string(email_template,
                                       { 'activation_key': instance.activation_key,
                                         'expiration_days': settings.NEWSLETTER_ACTIVATION_DAYS,
                                         'site': current_site,
                                         'user': instance,
                                         'email': instance.email 
                                        })

            send_mail(subject, message, settings.NEWSLETTER_FROM_EMAIL, [instance.email], fail_silently=True)
        return instance
开发者ID:petry,项目名称:django-newsletters,代码行数:35,代码来源:models.py


示例11: pending_message

def pending_message(from_address, to_address, subject, comment):
    """
    Create a pending message and send the activation email.
    """
    import random, sha
    from django.contrib.sites.models import Site
    from django.conf import settings

    # Store the email in the pending message db
    salt = sha.new(str(random.random())).hexdigest()[:5]
    activation_key = sha.new(salt+subject+from_address).hexdigest()

    # Fix the to_address if necessary
    to_address = ','.join(to_address)

    # Prepare the message to send to the user
    message = Pending_Messages(from_address=from_address,
                to_address=to_address,
                subject=subject,
                comment=comment,
                digest=activation_key)
    message.save()
    message_template = loader.get_template('activate_comment.txt')
    message_context = Context({ 'activation_key': activation_key,
                                'subject': subject,
                                'text': comment,
                                'to_address': to_address,
                                'from_address': from_address,
                                'site_url': Site.objects.get_current().domain
                                })
    message = message_template.render(message_context)
    # Send the email to the user
    subject = 'Activate the bug actions you prepared at Amancay'
    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [from_address])
开发者ID:dpaleino,项目名称:amancay,代码行数:34,代码来源:bugs.py


示例12: deactivate_subscription

    def deactivate_subscription(self, instance, email_template='newsletters/opt-out.html', send_email=True):
        """
        emails its deactivation key to the user.
        Returns the Subscription.

        To disable the email, call with send_email=False.
        """
        salt = sha.new(str(random.random())).hexdigest()[:5]
        deactivation_key = sha.new(salt+instance.email).hexdigest()[:16]
        
        instance.activation_key = deactivation_key
        instance.save()
        
        if send_email:
            from django.core.mail import send_mail
            from django.template.loader import render_to_string
            from django.contrib.sites.models import Site

            current_site = Site.objects.get_current()

            subject = ugettext('Confirm your unsubscription to %s' % (current_site.name))

            message = render_to_string(email_template,
                                       { 'deactivation_key': instance.activation_key,
                                         'site': current_site,
                                         'user': instance,
                                         'email': instance.email
                                        })

            send_mail(subject, message, settings.NEWSLETTER_FROM_EMAIL, [instance.email], fail_silently=True)
        return instance
开发者ID:petry,项目名称:django-newsletters,代码行数:31,代码来源:models.py


示例13: send_confirmation

 def send_confirmation(self, email_address):
     salt = sha.new(str(random())).hexdigest()[:5]
     confirmation_key = sha.new(salt + email_address.email).hexdigest()
     current_site = Site.objects.get_current()
     # check for the url with the dotted view path
     try:
         path = reverse("emailconfirmation.views.confirm_email",
             args=[confirmation_key])
     except NoReverseMatch:
         # or get path with named urlconf instead
         path = reverse(
             "emailconfirmation_confirm_email", args=[confirmation_key])
     activate_url = u"http://%s%s" % (unicode(current_site.domain), path)
     context = {
         "user": email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "confirmation_key": confirmation_key,
     }
     subject = render_to_string(
         "emailconfirmation/email_confirmation_subject.txt", context)
     # remove superfluous line breaks
     subject = "".join(subject.splitlines())
     message = render_to_string(
         "emailconfirmation/email_confirmation_message.txt", context)
     send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
               [email_address.email], priority="high")
     return self.create(
         email_address=email_address,
         sent=datetime.now(),
         confirmation_key=confirmation_key)
开发者ID:ParasBotadra,项目名称:django-email-confirmation,代码行数:31,代码来源:models.py


示例14: file_upload_view_verify

def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    # Check to see if unicode names worked out.
    if not request.FILES['file_unicode'].file_name.endswith(u'test_\u4e2d\u6587_Orl\xe9ans.jpg'):
        return HttpResponseServerError()

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = sha.new(value.read()).hexdigest()
        else:
            new_hash = sha.new(value).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    return HttpResponse('')
开发者ID:diofeher,项目名称:django-nfa,代码行数:25,代码来源:views.py


示例15: generate_image

    def generate_image(self, ipAddress):
        
        num_numbers = randint(1, 4)
        num_letters = 5 - num_numbers
        tipo_validacao = randint(0,1)
        pergunta=""
       
        imgtextL = ''.join([choice('QWERTYUOPASDFGHJKLZXCVBNM') for i in range(num_letters)])
        imgtextN = ''.join([choice('123456789') for i in range(num_numbers)])

        SALT = SECRET_KEY[:20]
        imgtext = ''.join([choice(imgtextL + imgtextN) for i in range(5)])
        im=Image.open(MEDIA_ROOT + 'images/jpg/captcha.jpg')
        draw = ImageDraw.Draw(im)
        font = ImageFont.truetype("/media/font/yellow_submarine.ttf", 30)
        draw.text((28,10),imgtext, font=font, fill=(255,255,255))
        temp = MEDIA_ROOT + "images/temp/" + ipAddress + '.jpg'
        tempname = ipAddress + '.jpg'
        im.save(temp, "JPEG")
       
        if tipo_validacao == 0:
            pergunta="n&uacute;meros"
            imghash = sha.new(SALT+imgtextN).hexdigest()
        if tipo_validacao == 1:
            pergunta="letras"
            imghash = sha.new(SALT+imgtextL).hexdigest()
        return {'captcha_img_name':tempname, 'hash_code_captcha':imghash, 'tipo_validacao':pergunta}
开发者ID:rogerhil,项目名称:heybaldock,代码行数:27,代码来源:captcha.py


示例16: save

  def save(self,request):
      new_user=super(UserForm,self).save(commit=False)
      new_user.username=new_user.username.lower()
      new_user.slug=slugify(new_user.username)
      new_user.is_active=False
      new_user.set_password(new_user.password)

      #create activation key
      salt = sha.new(str(random.random())).hexdigest()[:5]
      new_user.activation_key = sha.new(salt+new_user.username).hexdigest()

      new_user.save()
      #EMAIL USER OF ACTIVATION KEY
      from django.core.mail import send_mail
      if request.is_secure():
        current_site = 'https://%s' % request.get_host()
      else:
        current_site = 'http://%s' % request.get_host()

      subject = render_to_string('account/activation_email_subject.html',
                                 { 'site': current_site })
      # Email subject *must not* contain newlines
      subject = ''.join(subject.splitlines())

      message = render_to_string('account/activation_email.html',
                                 { 'activation_key': new_user.activation_key,
                                   'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                   'site': current_site })
      if getattr(settings,'EMAIL_HOST',False):
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
      return new_user
开发者ID:parulian1,项目名称:fashionment,代码行数:31,代码来源:forms.py


示例17: signIn

def signIn():
	print "Please input ID and Password"
	id_plain = raw_input("User ID : ")
	acc = open("access", "r")
	user_id = []
	user_pw = []
	for line in acc:
		user_id.append(line.split(":")[0])
		user_pw.append(line.split(":")[1].strip().split(", "))

	user_acc = dict(zip(user_id, user_pw))
	
	print user_acc
	
	while (id_plain in user_id) == False:
		print "Sorry, you are not registered member."
		yn = raw_input("Are you want to re-input your id? (Y / N)")
		if yn == 'Y' or yn == 'y':
			id_plain = raw_input("User ID : ")
		elif yn == 'N' or yn == 'n':
			print "Return to main menu"
			return 0
	password_plain = raw_input("User Password : ")
	password_encrypted = sha.new(password_plain).hexdigest()
	
	while (password_encrypted == user_acc[id_plain][0]) == False:
		print "Sorry, the entered password is not correct"
		yn = raw_input("Are you want to re-input your password? (Y / N)")
		if yn == 'Y' or yn == 'y':
			password_plain = raw_input("User Password : ")
			password_encrypted = sha.new(password_plain).hexdigest()
		elif yn == 'N' or yn == 'n':
			print "Return to main menu"
			return 0
	print "Hello", id_plain + ":", user_acc[id_plain][1:], "!"
开发者ID:Keastblack,项目名称:PythonWithKoreatech,代码行数:35,代码来源:hw04_02.py


示例18: create_email_change

    def create_email_change(self, user, new_email, send_email=True):
        """
        Create ActionRecord for email change and mails link
        with activation key to user's email.

        Pass ``send_email=False`` to disable sending the email.
        """
        if not user.email:
            user.email = new_email
            user.save()
            return
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        action_key = sha.new(salt+user.email).hexdigest()

        # And finally create the record.
        user.email_new = new_email
        user.save()
        record, created = self.get_or_create(user=user,
                                             type='E',
                                             defaults={'action_key': action_key})

        if send_email:
            current_domain = Site.objects.get_current().domain
            subject = "Change your email address at %s" % current_domain
            message_template = loader.get_template('accounts/password_reset.txt')
            message_context = Context({'site_url': '%s://%s' % (settings.SITE_PROTOCOL, current_domain),
                                       'action_key': record.action_key,
                                       'expiration_days': settings.ACTION_RECORD_DAYS,
                                       'user': user})
            message = message_template.render(message_context)
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        return record
开发者ID:gvidon,项目名称:blombum,代码行数:33,代码来源:managers.py


示例19: cadastrar_usuario

def cadastrar_usuario(request):
    dados = template_data(request)
    if request.method == 'POST':
        form = UsuarioForm(request.POST, auto_id=False, error_class=DivErrorList)
        if form.is_valid():
            u = form.save()
            salt = sha.new(str(random.random())).hexdigest()[:5]
            chave = sha.new(salt + u.username).hexdigest()
            expira = datetime.datetime.today() + datetime.timedelta(2)
            usuario = Usuario(conta=u,
                              cpf=form.cleaned_data['cpf'],
                              chave_de_ativacao=chave,
                              expiracao_chave=expira,
                              nascimento=form.cleaned_data['nascimento'],
                              sexo=form.cleaned_data['sexo'],
                              telefone=form.cleaned_data['telefone_contato'])
            request.session['pass'] = form.cleaned_data['senha']
            request.session['conta'] = u
            request.session['usuario_cadastro'] = usuario
            form = EnderecoForm()
            dados['form'] = form
            return render_to_response('finalizar_cadastro.html', dados,
                              context_instance=RequestContext(request))
        else:
            dados['form'] = form
            return render_to_response('cadastro.html', dados,
                                      context_instance=RequestContext(request))
    else:
        form = UsuarioForm()
        dados['form'] = form
    return render_to_response('cadastro.html', dados,
                              context_instance=RequestContext(request))
开发者ID:felipevieira,项目名称:EntregAqui,代码行数:32,代码来源:views.py


示例20: create_inactive_user

    def create_inactive_user(self, username, password, email, send_email=True):
        """
        Creates a new User and a new RegistrationProfile for that
        User, generates an activation key, and mails it.
        
        Pass ``send_email=False`` to disable sending the email.
        
        """
        # Create the user.
        new_user = User.objects.create_user(username, email, password)
        
        new_user.is_active = False
        new_user.save()
        
        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation_key = sha.new(salt+new_user.email).hexdigest()
        
        # And finally create the profile.
        new_profile = self.create(user=new_user, activation_key=activation_key)
        
        if send_email:
            current_domain = Site.objects.get_current().domain
            contxt=Context({ 'site_url': 'http://%s/' % current_domain,'activation_key': activation_key,'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
            message_template = loader.get_template('registration/activation_email.html')
            message=message_template.render(contxt)
            msg=EmailMultiAlternatives('Activate your account at Itechtalents',message,settings.DEFAULT_FROM_EMAIL,[new_user.email])
            msg.attach_alternative(message, "text/html")
            msg.send()
	return new_user    
开发者ID:msquaresystems,项目名称:itechtalents-12-10-2014,代码行数:30,代码来源:models.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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