2013-10-10 18 views
0

這個問題的由來是燒瓶教程http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask。在閱讀本教程中,我碰到這個功能來:檢查字符串是否爲unicode時,何時使用值比較而不是識別比較更好?

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods = ['PUT']) 
def update_task(task_id): 
    task = filter(lambda t: t['id'] == task_id, tasks) 
    if len(task) == 0: 
     abort(404) 
    if not request.json: 
     abort(400) 
    if 'title' in request.json and type(request.json['title']) != unicode: 
     abort(400) 
    if 'description' in request.json and type(request.json['description']) is not unicode: 
     abort(400) 
    if 'done' in request.json and type(request.json['done']) is not bool: 
     abort(400) 
    task[0]['title'] = request.json.get('title', task[0]['title']) 
    task[0]['description'] = request.json.get('description', task[0]['description']) 
    task[0]['done'] = request.json.get('done', task[0]['done']) 
    return jsonify({ 'task': task[0] }) 

該行使用值進行比較:

if 'title' in request.json and type(request.json['title']) != unicode: 

但這一行使用的身份比較:

if 'description' in request.json and type(request.json['description']) is not unicode: 

是否有一個原因,作者不一致?這兩個版本是否會提供相同級別的安全性?如果是這樣,pythonic方法是什麼?

+0

如果您在談論「!=」和「不是」,在最新版本中不推薦使用值比較「!=」,所以習慣使用「!=」的人有時會繼續使用 – user2753523

回答

1

我想更好地使用JSON模式來代替:

from jsonschema import validate, ValidationError 

schema = { 
    'type': 'object', 
    'properties': { 
     'title': { 
      'type': 'string', 
     }, 
     'description': { 
      'type': 'string', 
     }, 
     'done': { 
      'type': 'boolean', 
     }, 
    }, 
} 

try: 
    validate(request.get_json(), schema) 
except ValidationError: 
    abort(400) 

此外,如果你使用flask>=0.10request.json已被棄用,並更好地利用request.get_json()http://flask.pocoo.org/docs/api/#flask.Request.json

3

我寧願這樣:

if isinstance(request.json['title'], unicode): 
    pass 
+0

這樣更好比問題中代碼示例中的兩個版本中的任何一個都要好。 – BrenBarn

+0

如果你沒有'title'鍵,那麼你會得到'KeyError'異常。我認爲更好'isinstance(request.get_json()。get('title'),basestring)' – tbicr

+0

isinstance('asdasd',basestring) - > True(我的意思不是'unicode') – alexvassel

0

將兩個版本提供相同的安全水平? - >沒有

它不是一個更pythonic哪一個問題,這是一個問題,你想比較哪一級。考慮這一點,你就自己知道答案:

>>> a = 1 
>>> b = 1.0 
>>> a is b 
False 
>>> a == b 
True 
>>> id(a) 
12777000 
>>> id(b) 
14986000 
>>> a = 1 
>>> b = 1 
>>> a is b 
True 
>>> a == b 
True 
>>> id(a) 
12777000 
>>> id(b) 
12777000 

但要注意這一點:

>>> a=1000 
>>> b=1000 
>>> a is b 
False 

>>> a='good' 
>>> b='good' 
>>> a is b 
True 
>>> a='啊' 
>>> b='啊' 
>>> a is b 
False 
>>> a==b 
True 

的原因是緩衝池的概念。 所以,當你想比較,「=」和「!=」比較安全

ID,「是」和「不」是安全的(但千萬注意緩衝池)