处理Flask中的POST JSON错误

时间:2012-11-10 22:27:01

标签: python http flask

我正在编写API并期待JSON中的数据。我的函数运行良好,并将数据存储在SQLite中,如下所示:

if request.method == 'POST':
    if request.headers['Content-Type'] == 'application/json':
        db = get_db()
        data = json.loads(request.data)
        row = (data['lat'], data['long'], data['address'], data['name'])
        db.execute('INSERT INTO places (lat, long, address, name) values (?, ?, ?, ?)', row)
        db.commit()
        resp = Response(status=200, mimetype='application/json')
        return resp

如果有人发送的POST包含错误的JSON字段(缺少latlongaddressname),则Flask会抛出错误。

处理此问题的最佳方法是什么?

我尝试过:

if not 'lat' in data or if not 'long' in data or ....

但是data只是一个字符串而不是字典。所以我有两个问题:

  1. 如何将字段引用为上面的字典(data['lat'] ...)?
  2. 处理此错误的适当方法是什么?

1 个答案:

答案 0 :(得分:8)

当您使用data = json.loads(request.data)从JSON加载数据时,您将拥有python结构。

如果那时不是字典,那么无论发送给你的请求是什么,都没有正确的JSON结构(例如,可能是一个列表)。

在这种情况下,我会使用try / execept

try:
    data = json.loads(request.data)
    row = (data['lat'], data['long'], data['address'], data['name'])
except (ValueError, KeyError, TypeError):
    # Not valid information, bail out and return an error
    return SomeErrorResponse

如果request.data无效JSON,或者data不是具有正确密钥的字典,则会引发异常。列出的三个例外是可能出现的各种错误模式:

>>> import json
>>> json.loads('nonsense')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 338, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> 'ouea'['abc']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str
>>> [0]['oue']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> {}['oue']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'oue'