1

Im currently working on a MongoDB backed RESTFUL API with flask... However, Ive got a zone search query set up with find_one(), however as soon as I try making it a larger query with multiple results using find(), I get the following error on postman :

UnboundLocalError: local variable 'output' referenced before assignment

this is the code that works, however it only returns one document from the query:

@app.route('/active_jobs/<zone>', methods = ['GET'])
def get_one_zone(zone):

ajobs = mongo.db.ajobs

q = ajobs.find_One({'zone' : zone})

output = {}

output = ({
'zone': q['zone'], 'jobdate' : q['jobdate'],
'jobtime' : q['jobtime'],'client': q['client'],
})

return jsonify({output})

once I try to chage to get all results making it find() it doesnt work

@app.route('/active_jobs/<zone>', methods = ['GET'])
def get_one_zone(zone):

ajobs = mongo.db.ajobs

q = ajobs.find({'zone' : zone})

output = {}

output = ({
'zone': q['zone'], 'jobdate' : q['jobdate'],
'jobtime' : q['jobtime'],'client': q['client'],
})

return jsonify({output})

Ps. Im a total newbie in the programming world so if you could use simple examples that would be much appreciated.

AOH
  • 31
  • 2

2 Answers2

1

This is probably because 'find_One' in mongo will return only 1 document as a dictionary whereas find will return multiple documents as a list of dictionaries. jsonify does not work on a list as seen here: How do I `jsonify` a list in Flask?.

You can use json.dumps instead as the answers there suggest.

Community
  • 1
  • 1
ujjwal-gupta
  • 123
  • 1
  • 12
0

For security reasons instead of returning a plain list, is recommended to return a dict with a list, something like:

{ 
  'data': [1,2,3,4]
}

jsonify will handle this just fine.

By the way, I have built a lightweight framework for building restful apis and the default database engine used is mongodb, so i think you will probably find it helpful. Here's the code: https://github.com/sebastiandev/peach

There are some step by step examples for it. If you have any other doubt, please let me know and I'll try to help you with it.

Sebastian
  • 1,243
  • 1
  • 18
  • 34