Python 函数在应该返回True时返回false。编码问题?
我目前正在开发一个验证函数,该函数基于表达式(if语句)返回Python 函数在应该返回True时返回false。编码问题?,python,json,base64,Python,Json,Base64,我目前正在开发一个验证函数,该函数基于表达式(if语句)返回True或False。标头是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
True
或False
。标头是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))
这里的问题是使用
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
我认为我们需要更多的背景。对这个函数的调用是什么样子的?传递给它的数据是什么?