decode的时候,用utf8还是ascii? 如何选择?

来源:6-2 获取Token令牌

qq_书山压力大EE_0

2018-07-01

token.py的get_token函数中 最后, 

`t = {'token': token.decode('ascii')}`    

 对于bytes类型的字符串, 什么时候decode('utf8')什么时候decode('ascii')? 这里能用decode('utf8')代替decode('ascii')吗?

写回答

3回答

老卢123123

2018-07-27

def generate_auth_token(uid,ac_type,scope=None,expiration=7200):
    '''
    :param uid: 用户id
    :param ac_type:active_type,客户端类型
    :param scope: 作用域
    :param expiration: 有效时间
    :return: token
    '''
    s = Serializer(current_app.config['SECRET_KEY'],
                   expires_in=expiration)
    return s.dumps({
        'uid':uid,
        'type':ac_type.value,
    }).decode('utf-8')

如上述代码,在生成token都方法里,直接return decode('utf-8')后都token,运行成功,目前没发现问题

@api.route('',methods=['POST'])
def get_token():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL:User.verify
    }
    identity = promise[form.type.data](
        form.account.data,
        form.secret.data
    )
    # identity为用户uid,开始生成token
    expiration = current_app.config['TOKEN_EXPIRATION']
    token = generate_auth_token(identity['uid'],
                                form.type.data,
                                None,
                                expiration)
    t = {
        'token':token
    }
    return Success(msg=t)

postman收到都返回也是正确的

{
    "error_code": 0,
    "msg": {
        "token": "eyJhbGciOiJIUzI1NiIsImlhdCI6MTUzMjY3MTk0NiwiZXhwIjoxNTMyNzU4MzQ2fQ.eyJ1aWQiOjE0LCJ0eXBlIjoxMDB9.t4Q_-ju8LclM3yBVfu5Yb_0_ejqw4ZJZiWGjz7GqfiI"
    },
    "request": "POST /v1/token"
}


0
0

老卢123123

2018-07-27

上一期的高级编程中,有一节课,发送电子邮件重置密码的

当时使用都是decode('utf-8')'

    def generate_token(self, expiration=600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'id': self.id}).decode('utf-8')

验证token时也是encode('utf-8)

    @staticmethod
    def reset_password(token, new_password):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False
        user = User.query.get(data.get('id'))
        if user is None:
            return False
        user.password = new_password
        db.session.commit()
        return True

A`为什么现在需要使用decode('ascii')?

B`是什么原因导致两种情况下都不同用法,我们如何选择?

0
2
7七月
这里我觉得你太纠结了吧,这个编码人家是怎么编码的你就要用什么呀。
2018-07-28
共2条回复

7七月

2018-07-05

utf-8会报错

0
4
老卢123123
回复
7七月
老师,我补充在回答里了,烦请您看一下
2018-07-27
共4条回复

Python Flask高级编程之RESTFul API前后端分离精讲

RESTFul+权限管理+token令牌+扩展flask=提升编程思维

2037 学习 · 359 问题

查看课程