'a dönüştürüyorum Bir uygulama geliştiriyorum ve bazı testler yapmak istiyorum. Yanıt verisini test istemcisinden JSON'a dönüştürmem gerekiyor.Test istemci verilerini JSON
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)
testler:
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()
Ben JSON response.data
dönüştürmeye çalıştığınızda, aşağıdaki hatayı olsun: Nasıl
TypeError: the JSON object must be str, not 'bytes'
düzeltebilirim Bu hata ve JSON verilerini almak?
Hiçbir "response.json" yoktur. Onları doğru kodek ile çözmektense, bayt üzerinde “str” yi çağırmak optimal değildir. – davidism
Bu yalnızca JSON'un varsayılan kodek olarak UTF-8 kullanması nedeniyle çalışır. Açık kodek olmadan str() 'nin kullanılması nadiren iyi bir fikirdir. –
Açıklama için teşekkürler, Martijn. –