Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How return list on Python and Flask? [duplicate]

I'm trying to return this list in flask. Teacher is a class and returns objects.

@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
  teachers = []
  for teacher in Teacher.objects:
    teachers.append(teacher)
  return teachers

This code returns the typical error of TypeError: 'list' object is not callable The view function did not return a valid response.

I'm going crazy and I don't know what's going on. Does anyone know?

Thank you!!

EDIT:

I've already worked it out. The problem was not how to return the list, the problem was the serialization in JSON of the objects.

@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
  teachers = []
  for teacher in Teacher.objects:
     teacherJson = teacher.to_json()
     teacherData = json.loads(teacherJson)
     teachers.append(teacherData)
  return jsonify({'teachers': teachers})

Thanks for your help.

like image 590
mollywind Avatar asked Jan 02 '19 09:01

mollywind


People also ask

Can I return list in Flask?

You can't return a list from a view: HTTP is for moving text around. If you're trying to use it as an endpoint for an API, then you can encode it in some way like JSON and parse that in the code that uses the API.

How do you use Jsonify in Flask?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.


1 Answers

You can't return a list directly from flask view.please try to jsonify

from flask import jsonify
@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
   teachers = []
   for teacher in Teacher.objects:
      teachers.append(teacher)
   return jsonify(teachers)
like image 180
shijin Avatar answered Sep 17 '22 15:09

shijin