2016-09-26 171 views
1

我目前正在使用基于表达式(if语句)返回TrueFalse的验证函数。头是base64解码,然后json.loads用于将其转换为字典。这里是方法:函数返回True时返回false。编码问题?

@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 

如果参数是基地64解码并转换为字典,检查只会失败。为什么?任何帮助,将不胜感激。

编辑:根据要求,这里是我怎么称呼该方法。 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)) 
+0

我认为我们需要更多的上下文。这个函数的调用是什么样的?数据被传递给它? – sdsmith

回答

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 
+0

好的,谢谢。我应该看到这一点。 – Corgs