简体   繁体   English

将测试客户端数据转换为JSON

[英]Convert test client data to JSON

I'm building an app and I want to make some tests. 我正在构建一个应用程序,我想做一些测试。 I need to convert the response data from the test client to JSON. 我需要将响应数据从测试客户端转换为JSON。

The app: 该应用程序:

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)

The tests: 测试:

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()

When I try to convert response.data to JSON, I get the following error: 当我尝试将response.data转换为JSON时,我收到以下错误:

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

How can I fix this error and get the JSON data? 如何修复此错误并获取JSON数据?

Flask 1.0 adds the get_json method to the response object, similar to the request object. Flask 1.0将get_json方法添加到响应对象,类似于请求对象。 It handles parsing the response data as JSON, or raises an error if it can't. 它将响应数据解析为JSON,如果不能,则引发错误。

data = response.get_json()

Prior to that, and prior to Python 3.6, json.loads expects text, but data is bytes. 在此之前,在Python 3.6之前, json.loads需要文本,但data是字节。 The response object provides the method get_data , with the as_text parameter to control this. 响应对象提供方法get_data ,使用as_text参数来控制它。

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

更新:尝试resp = json.loads(str(response.data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM