2016-09-26 173 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