Python werkzeug.security 模块,generate_password_hash() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用werkzeug.security.generate_password_hash()

项目:fame    作者:certsocietegenerale    | 项目源码 | 文件源码
def create_user(name, email, groups, default_sharing, permissions, password=None):
    user = User.get(email=email.lower())

    if user:
        print "/!\ User with this email address already exists."
    else:
        user = User({
            'name': name,
            'email': email.lower(),
            'groups': groups,
            'default_sharing': default_sharing,
            'permissions': permissions,
            'enabled': True
        })
        if password:
            user['pwd_hash'] = generate_password_hash(password)
        user.save()
        print "[+] User created."

        user.generate_avatar()
        print "[+] Downloaded avatar."

    return user
项目:GOKU    作者:bingweichen    | 项目源码 | 文件源码
def add(username, password, **kwargs):
    """
    :param username:
    :type username:
    :param password:
    :type password:
    :param kwargs:
    :type kwargs:
    :return:
    :rtype:
    """
    hashed_password = generate_password_hash(password)
    user = User.create(
        username=username,
        password=hashed_password,
        **kwargs)
    return user
项目:to-vendendo    作者:anapaulagomes    | 项目源码 | 文件源码
def register_view(self):
        form = RegistrationForm(request.form)
        if helpers.validate_form_on_submit(form):
            user = User()

            form.populate_obj(user)
            user.password = generate_password_hash(form.password.data)

            db.session.add(user)
            db.session.commit()

            login.login_user(user)
            return redirect(url_for('.index'))

        link = '<p>Already have an account? <a href="' \
            + url_for('.login_view') + '">Click here to log in</a></p>'
        self._template_args['form'] = form
        self._template_args['link'] = link
        return super(AuthenticationView, self).index()
项目:dockmaster    作者:lioncui    | 项目源码 | 文件源码
def registry():
    if request.method == 'POST':
        user_id = Standardlib.create_uuid()
        username = request.form.get('username',None)
        password = request.form.get('password', None)
        email = request.form.get('email', None)
        try:
            newuser = models.User(uuid = user_id, username = username, 
                                    password = generate_password_hash(password),
                                    email = email, timestamp = datetime.utcnow())
            db.session.add(newuser)
            db.session.commit()
            return jsonify(result="sucessfull")
        except:
            return jsonify(result = "failed")
        finally:
            db.session.close()
    return redirect('login')
项目:dockmaster    作者:lioncui    | 项目源码 | 文件源码
def change_passwd():
    if session.get('login_in',None):
        if session.get('username',None):
            oldpassword = request.values['oldpassword']
            newpassword = request.values['newpassword']
            try:
                user = models.User.query.filter_by(username = session['username']).first()
                if check_password_hash(user.password, oldpassword):
                    user.password = generate_password_hash(newpassword)
                    db.session.add(user)
                    db.session.commit()
                    return jsonify(result="change sucessfull")
                else:
                    return jsonify(result="change failed")
            except:
                db.session.rollback()
                return jsonify(result="change failed")
            finally:
                db.session.close()
        else:
            return redirect('/login')
    else:
        return redirect('/login')
项目:TypingSystem    作者:TrustMe5    | 项目源码 | 文件源码
def register():                     #??????
    registerform=RegisterForm()
    if registerform.validate_on_submit():
        if User.query.filter_by(name=registerform.name.data).first():
            flash("The username %s is already exist !"%registerform.name.data)
            return redirect(url_for('register'))
        elif User.query.filter_by(student_number=registerform.student_number.data).first():
            flash("The student_number is already exist !")
            return redirect(url_for('register'))
        else:
            inset=User(classes=registerform.year.data+registerform.major.data+registerform.grade.data+"?",student_number=registerform.student_number.data,name=registerform.name.data,password=generate_password_hash(registerform.password.data),admin=0,onlineTime=0,numofSubmit=0,recentsubmitTime='Never Submittied',averageSpeed=0)
            db.session.add(inset)                         #?????generate_password_hash?????hash???????
            db.session.commit()
            flash('????????')
            return redirect('/auth/login')
    return render_template('register.html',register=registerform)
项目:TypingSystem    作者:TrustMe5    | 项目源码 | 文件源码
def modifypwd(username):                                             #????????
    if username!=session.get('name'):             #?????????????????????
        return redirect('/auth')
    else:
        form=ChangePersonalPwd()
        user=User.query.filter_by(name=username).first()
        if form.validate_on_submit():
           if user is not None and check_password_hash(user.password,form.oldpassword.data):
               if form.newpassword.data!=form.confirmpassword.data:
                  flash('??????????')
               else:
                  user.password=generate_password_hash(form.newpassword.data)
                  db.session.commit()
                  flash('?????')
                  return redirect('/auth')
           else:
               flash('??????????????')
    return render_template('modifypwd.html',form=form,writer=session.get('name'))
项目:flask_api    作者:nullcc    | 项目源码 | 文件源码
def create():
    """
    ????
    :return:
    """
    username = request.values.get("username")
    password = request.values.get("password")
    email = request.values.get("email")
    gender = int(request.values.get("gender"))

    password_hash = generate_password_hash(password, method='pbkdf2:sha1', salt_length=8)
    user = User(username=username,
                password_hash=password_hash,
                email=email,
                gender=gender)
    user.save()
    return success()
项目:WinTheMini    作者:j10sanders    | 项目源码 | 文件源码
def register_post():
    try:
        if request.form["password"] != request.form["password2"]:
            flash("Your password and password verification didn't match.",
                  "danger")
            return redirect(url_for("register_get"))
        if len(request.form["password"]) < 8:
            flash("Your password needs to be at least 8 characters", "danger")
            return redirect(url_for("register_get"))
        user = User(name=request.form["username"],
                    password=generate_password_hash(request.form["password"]),
                    email=request.form["email"])
        session.add(user)
        allusers = session.query(User).all()
        for users in allusers:
            session.add(user.follow(users))
            session.add(users.follow(user))
        session.commit()
        flash("User successfully registered", "success")
        login_user(user)
        return redirect(request.args.get("next") or url_for("entries"))
    except IntegrityError:
        flash("The username or email was already taken." +
              " Maybe you need to reset your password (below)?", "danger")
        session.rollback()
        return redirect(url_for("register_get"))
项目:WinTheMini    作者:j10sanders    | 项目源码 | 文件源码
def pwreset_post(id):
    if request.form["password"] != request.form["password2"]:
        flash("Your password and password verification didn't match.", "danger")
        return redirect(url_for("pwreset_get", id = id))
    if len(request.form["password"]) < 8:
        flash("Your password needs to be at least 8 characters", "danger")
        return redirect(url_for("pwreset_get", id = id))
    user_reset = session.query(PWReset).filter_by(reset_key=id).one()
    #session.query(User).filter_by(id=user_reset.user.id).one()
    #gi(user_reset.user_id, "PRINTING ID")
    try:
        session.query(User).filter_by(id = user_reset.user_id).update({'password': generate_password_hash(request.form["password"])})
        session.commit()
    except IntegrityError:
        flash("Something went wrong", "danger")
        session.rollback()
        return redirect(url_for("entries"))
    user_reset.has_activated = True
    session.commit()
    flash("Your new password is saved.", "success")
    #login_user(user)
    return redirect(url_for("entries"))
项目:BackManager    作者:linuxyan    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:luminance    作者:nginth    | 项目源码 | 文件源码
def set_password(self, password):
        self.pw_hash = generate_password_hash(password)
项目:openedoo    作者:openedoo    | 项目源码 | 文件源码
def hashing_werkzeug(password):
    hashpw = generate_password_hash(password)
    return hashpw
项目:zlktqa    作者:NunchakusHuang    | 项目源码 | 文件源码
def password(self,rawpwd):
        self._password = generate_password_hash(rawpwd)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:BookLibrary    作者:hufan-akari    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:IntegraTI-API    作者:discentes-imd    | 项目源码 | 文件源码
def encrypt_password():
    """
    Verify if the route is for password reset or user create, then encrypts the password.
    """
    if request.json is None or not 'password' in request.json:
        return
    if str(request.url_rule) == '/auth/user/' and request.method == 'POST' \
    or str(request.url_rule) == '/auth/user/resetpassword/' and request.method == 'PUT':
        request.json['password'] = generate_password_hash(request.json['password'])
项目:circleci-demo-python-flask    作者:CircleCI-Public    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:quokka_ng    作者:rochacbruno    | 项目源码 | 文件源码
def create_user(**data):
    if 'username' not in data or 'password' not in data:
        raise ValueError('username and password are required.')

    data['_id'] = data['username']
    data['password'] = generate_password_hash(
        data.pop('password'),
        method='pbkdf2:sha256'
    )
    # current_app.db.users.insert_one(data)
    current_app.db.insert('users', data)
    return data
项目:zimfarm    作者:openzim    | 项目源码 | 文件源码
def upsert_user(username: str, password: str=None, scope: dict=None):
    filter = {'username': username}

    set = {}
    if password is not None:
        set['password_hash'] = generate_password_hash(password)
    if scope is not None:
        set['scope'] = UserJWT.validate_scope(scope)

    return UsersCollection().find_one_and_update(filter, {'$set': set}, {'_id': False, 'password_hash': False},
                                                 return_document=ReturnDocument.AFTER, upsert=True)
项目:zimfarm    作者:openzim    | 项目源码 | 文件源码
def initialize():
    from werkzeug.security import generate_password_hash
    import mongo

    def create_rabbit_init_user(username, password):
        number_of_tries = 100
        while number_of_tries:
            try:
                number_of_tries -= 1
                user.update_rabbitmq_user(username, password)
                break
            except urllib.error.URLError:
                sleep(5)
        else:
            raise Exception()

    mongo.ZimfarmDatabase().initialize()
    users = mongo.UsersCollection()
    if users.find_one() is None:
        username = getenv('INIT_USERNAME', 'admin')
        password = getenv('INIT_PASSWORD', 'admin_pass')
        users.insert_one({
            'username': username,
            'password_hash': generate_password_hash(password),
            'scope': {'admin': True}
        })
        create_rabbit_init_user(username, password)
项目:MoegirlUpdater    作者:kafuuchino    | 项目源码 | 文件源码
def password(self,password):
        self.password_hash=generate_password_hash(password)
项目:Cynops    作者:phantom0301    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:Leics    作者:LeicsFrameWork    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:do-portal    作者:certeu    | 项目源码 | 文件源码
def password(self, password):
        self._password = generate_password_hash(
            password, method='pbkdf2:sha512:100001', salt_length=32
        )
项目:myproject    作者:dengliangshi    | 项目源码 | 文件源码
def password(self, password):
        """Set password.
        """
        self.password_hash = generate_password_hash(password)
项目:InfoSub    作者:CoderHito    | 项目源码 | 文件源码
def __setattr__(self, key, value):
        if key == "password":
            if not value or len(value) == 0:
                return
            value = str(generate_password_hash(value))
        super(User, self).__setattr__(key, value)
项目:monolith    作者:Runnerly    | 项目源码 | 文件源码
def set_password(self, password):
        self.password = generate_password_hash(password)
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def _set_password(self, password):
        """Generates a password hash for the provided password."""
        if not password:
            return
        self._password = generate_password_hash(password)

    # Hide password encryption by exposing password field only.
项目:sentiment-analysis    作者:kasheemlew    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:graphql-pynamodb    作者:yfilali    | 项目源码 | 文件源码
def serialize(self, value):
        if is_password_hash(value):
            return value
        return generate_password_hash(value)
项目:Simpleblog    作者:Blackyukun    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:zsky    作者:wenguonideshou    | 项目源码 | 文件源码
def create_user(name,password,email):
    if name is None:
        name = raw_input('?????(??admin):') or 'admin'
    if password is None:
        password = generate_password_hash(getpass('??:'))
    if email is None:
        email=raw_input('Email??:')
    user = User(name=name,password=password,email=email)
    db.session.add(user)
    db.session.commit()
    print u"???????!"
项目:zsky    作者:wenguonideshou    | 项目源码 | 文件源码
def changepassword(newpassword):
    name = raw_input(u'?????:')
    thisuser = User.query.filter_by(name=name).first()
    if not thisuser:
        print u"?????,????????!"
        name = raw_input(u'?????:')    
        thisuser = User.query.filter_by(name=name).first()
    if newpassword is None:
        newpassword = generate_password_hash(getpass(u'???:'))
    thisuser.password=newpassword
    db.session.add(thisuser)
    db.session.commit()
    print u"?????,??????!"
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:GWMMS    作者:lvhuiyang    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:Panda-s-Backend    作者:kyokuheishin    | 项目源码 | 文件源码
def register():
    if 'username' in session:
        if session['username'] != "admin":
            return jsonify(status_error_permission_denied)
        else:
            if request.method == 'POST':
                if Users.query.filter_by(USERNAME=request.form['username']).first() is not None:
                    return jsonify(status_error_already_existed_username)
                else:
                    user = Users(request.form['username'], generate_password_hash(request.form['password']),
                                 request.form['phone_number'], request.form['address'])
                    try:
                        db.session.add(user)
                        db.session.commit()
                    except:
                        return jsonify(status_error_unknown_error)
                    else:
                        return redirect(url_for('index'))
    else:
        return jsonify(status_error_permission_denied)
    return render_template("user/register.html")
项目:Panda-s-Backend    作者:kyokuheishin    | 项目源码 | 文件源码
def admin():
        user = Users.query.filter_by(USERNAME='admin').first()
        user.USERNAME = "admin"
        user.PASSWORD = generate_password_hash("james1")
        db.session.add(user)
        db.session.commit()
        return "????"
项目:Panda-s-Backend    作者:kyokuheishin    | 项目源码 | 文件源码
def user_edit():
    if 'username' in session:
        if session['username'] != "admin":
            return jsonify(status_error_permission_denied)
        else:
            if request.method == "POST":
                if Users.query.filter_by(ID_USER=request.form['id_user']).first() is None:
                    return jsonify(status_error_does_not_exist_username)
                else:
                    user = Users.query.filter_by(ID_USER=request.form['id_user']).first()
                    user.USERNAME = request.form['username']
                    user.PASSWORD = generate_password_hash(request.form['password'])
                    user.MOBILE_NUMBER = request.form['phone_number']
                    user.ADDRESS = request.form['address']

                    try:
                        db.session.add(user)
                        db.session.commit()
                    except:
                        return jsonify(status_error_unknown_error)
                    else:
                        return jsonify(status_ok_edit_successfully)
    else:
        return jsonify(status_error_permission_denied)

    return render_template('user/user_edit.html')
项目:Panda-s-Backend    作者:kyokuheishin    | 项目源码 | 文件源码
def user_password_change():
    if 'username' in session:
        if session['username'] != "admin":
            if request.method == "POST":
                if Users.query.filter_by(USERNAME=session['username']).first() is None:
                    return jsonify(status_error_does_not_exist_username)
                else:
                    user = Users.query.filter_by(USERNAME=session['username']).first()
                    if check_password_hash(user.PASSWORD, request.form['password']) is False:
                        return jsonify(status_error_wrong_username_or_password)
                    else:
                        user.PASSWORD = generate_password_hash(request.form['password_new'])
                        try:
                            db.session.add(user)
                            db.session.commit()
                        except:
                            return jsonify(status_error_unknown_error)
                        else:
                            return jsonify(status_ok_edit_successfully)
            else:
                return render_template('user/user_change_password.html')
        else:
            if request.method == "POST":
                if Users.query.filter_by(ID_USER=request.form['id_user']).first() is None:
                    return jsonify(status_error_does_not_exist_username)
                else:
                    user = Users.query.filter_by(ID_USER=request.form['id_user']).first()
                    user.PASSWORD = generate_password_hash(request.form['password_new'])
                    try:
                        db.session.add(user)
                        db.session.commit()
                    except:
                        return jsonify(status_error_unknown_error)
                    else:
                        return jsonify(status_ok_edit_successfully)
            else:
                return render_template('user/user_change_password_admin.html')

    else:
        return  jsonify(status_error_permission_denied)
项目:Plog    作者:thundernet8    | 项目源码 | 文件源码
def raw_password(self, password):
        """
        ?? setter,?????????????
        :param password: ???????
        :return:
        """
        self.password = generate_password_hash(password)
        # mongo.db.users.update_one({
        #     'user_id': self.user_id
        # }, {
        #     '$set': {
        #         'password': self.password
        #     }
        # })
项目:Plog    作者:thundernet8    | 项目源码 | 文件源码
def add_user(**kwargs):
        """
        ???????
        :param kwargs: ???????
        :return: ?????? True,???? False
        """
        if 'name' not in kwargs or 'email' not in kwargs or 'password' not in kwargs:
            return False  # ??????
        user = mongo.db.users.find_one({'$or': [{'name': kwargs['name']}, {'email': kwargs['email']}]})
        if user:
            return False  # ?????????
        kwargs['user_id'] = get_next_sequence('user_id')
        if 'nickname' not in kwargs:
            kwargs['nickname'] = kwargs['name']  # ???????????
        kwargs['password'] = generate_password_hash(str(kwargs['password']))
        if not mongo.db.users.find_one():
            kwargs['role_id'] = 1  # ??????????
        else:
            kwargs['role_id'] = 3  # ???????????,??????,??????????????????????
        kwargs['avatar_hash'] = hashlib.md5(kwargs['email'].encode('utf-8')).hexdigest()
        kwargs['status'] = 'active'
        kwargs['confirmed'] = 0
        kwargs['create_at'] = int(time.time())
        kwargs['update_at'] = int(time.time())

        try:
            result = mongo.db.users.insert_one(kwargs)
            return User(_id=result.inserted_id)
        except:
            return False
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:Mastering-Python-Networking    作者:PacktPublishing    | 项目源码 | 文件源码
def set_password(self, password):
        self.password_hash = generate_password_hash(password)
项目:MyCoin_Backend    作者:Four-Undefined    | 项目源码 | 文件源码
def password(self,password) :
        self.password_hash = generate_password_hash(password)
项目:fanclley    作者:guerbai    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:fame    作者:certsocietegenerale    | 项目源码 | 文件源码
def change_password(user, password):
    user.update_value('pwd_hash', generate_password_hash(password))
    user.update_value('auth_token', auth_token(user))
项目:PilosusBot    作者:pilosus    | 项目源码 | 文件源码
def password(self, password):
        self.password_hash = generate_password_hash(password)
项目:web_develop    作者:dongweiming    | 项目源码 | 文件源码
def _set_password(self, plaintext):
        self._password = generate_password_hash(plaintext)
项目:catpel_backend    作者:tangxiangru    | 项目源码 | 文件源码
def password(self,password):
        self.password_hash = generate_password_hash(password)