函数返回false时应该返回True。编码问题?

时间:2016-09-26 04:02:41

标签: python json base64

我目前正在开发一个验证函数,它根据表达式(if语句)返回TrueFalse。标头是base64解码后,然后使用json.loads将其转换为dict。这是方法:

    @staticmethod
    def verify(rel):
        if not('hello' in rel and rel['hello'] is 'blah' and 'alg' in rel and rel['alg'] is 'HS256'):
            return False
        return True

如果参数是base 64解码并转换为dict,则检查失败。为什么?任何帮助将不胜感激。

编辑:根据请求,这是我如何调用该方法。 Python 3.5.2

p = {'hello': 'blah', 'alg': 'HS256'}
f = urlsafe_b64encode(json.dumps(p).encode('utf-8'))
h = json.loads(str(urlsafe_b64decode(f))[2:-1], 'utf-8')
print(verify(h))

1 个答案:

答案 0 :(得分:2)

这里的问题是您使用is运算符来检查字符串的相等性。 is运算符检查它的两个参数是否引用同一个对象,这不是您想要的行为。要检查字符串是否相等,请使用相等运算符:

 def verify(rel):
    if not('hello' in rel and rel['hello'] == 'blah' and 'alg' in rel and rel['alg'] == 'HS256'):
        return False
    return True
相关问题