这个问题的起源是http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask上的烧瓶教程。在阅读本教程时,我遇到了这个功能:
@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的方法是什么?