函数在应该返回 True 时返回 false。编码问题?
Function returning false when it should be returning True. Encoding issue?
我目前正在研究 returns True
或 False
基于表达式(if 语句)的验证函数。 header 是 base64 解码,然后 json.loads
用于将其转换为字典。方法如下:
@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 解码并转换为字典时,检查才会失败。为什么?任何帮助将不胜感激。
编辑:根据要求,这是我调用该方法的方式。 Python3.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
我目前正在研究 returns True
或 False
基于表达式(if 语句)的验证函数。 header 是 base64 解码,然后 json.loads
用于将其转换为字典。方法如下:
@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 解码并转换为字典时,检查才会失败。为什么?任何帮助将不胜感激。
编辑:根据要求,这是我调用该方法的方式。 Python3.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