Sto costruendo un'applicazione e voglio fare dei test. Devo convertire i dati di risposta dal client di test a JSON.Converti i dati del client di test in JSON
L'applicazione:
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)
I test:
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()
Quando cerco di convertire response.data
a JSON, ottengo il seguente errore:
TypeError: the JSON object must be str, not 'bytes'
Come posso risolvere questo errore e ottenere i dati JSON?
Non c'è 'response.json'. Chiamare 'str' su byte invece di decodificarli con il codec corretto non è ottimale. – davidism
Funziona solo perché JSON sembra utilizzare UTF-8 come codec predefinito. Usare 'str()' senza un codec esplicito è raramente una buona idea. –
Grazie per il chiarimento, Martijn. –