本文介绍了将测试客户端数据转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个应用程序,我想做一些测试。我需要将来自测试客户端的响应数据转换为JSON。
应用程序:
tasks = [ {'id':1,'title':u'Buy groceries','description':u'Milk,奶酪,比萨,水果,Tylenol','完成':False }, {'id':2,'title':u'Learn Python','description':u'需要在网上找到一个好的Python教程','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 task]}) if __name__ =='__main__': app.run (debug = True)测试:
class MyTestCase(unittest.TestCase): def setUp(self): myapp.app.confi g ['TESTING'] = True self.app = myapp.app.test_client() $ b $ 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()当我尝试转换响应.data 到JSON,我得到以下错误:
TypeError:JSON对象必须是str ,而不是'字节'如何解决这个错误并获取JSON数据?
解决方案您需要获取响应数据作为文本,但默认是字节。响应对象提供了 get_data 来控制这个。
data = json.loads(response.get_data(as_text = True))
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.
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:
TypeError: the JSON object must be str, not 'bytes'How can I fix this error and get the JSON data?
解决方案You need to get the response data as text, but the default is bytes. The response object provides the method get_data to control this.
data = json.loads(response.get_data(as_text=True))
更多推荐
将测试客户端数据转换为JSON
发布评论