【问题标题】:Convert test client data to JSON将测试客户端数据转换为 JSON
【发布时间】:2015-05-07 01:56:00
【问题描述】:

我正在构建一个应用程序,我想进行一些测试。我需要将测试客户端的响应数据转换为 JSON。

应用程序:

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

app = Flask(__name__, static_url_path="")

@app.route('/myapp/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': [task for task in tasks]})

if __name__ == '__main__':
    app.run(debug=True)

测试:

class MyTestCase(unittest.TestCase):
    def setUp(self):
        myapp.app.config['TESTING'] = True
        self.app = myapp.app.test_client()

    def test_empty_url(self):
        response = self.app.get('/myapp/api/v1.0/tasks')
        resp = json.loads(response.data)
        print(resp)

if __name__ == '__main__':
    unittest.main()

当我尝试将 response.data 转换为 JSON 时,我收到以下错误:

TypeError: the JSON object must be str, not 'bytes'

如何修复此错误并获取 JSON 数据?

【问题讨论】:

    标签: python json testing flask


    【解决方案1】:

    Flask 1.0 将get_json 方法添加到响应对象中,类似于请求对象。它将响应数据解析为 JSON,如果不能,则会引发错误。

    data = response.get_json()
    

    在此之前,在 Python 3.6 之前,json.loads 需要文本,但 data 是字节。响应对象提供了方法get_data,带有as_text参数来控制它。

    data = json.loads(response.get_data(as_text=True))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2021-12-16
      • 2018-02-28
      • 1970-01-01
      • 2019-11-27
      相关资源
      最近更新 更多