1

I'm having a single test for retrieve documents in a single page, i know it's not correct to do in a single page; but it's just to understand all this work like pure script, not for an api restful.

My problem is when i use:

print (jsonify({'result' : output}))

i've get this error:

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

when I replace this line by

print ( output)  

have no erros and have the documents.

How i can to specify a context for jsonify ? inside another context ? because i'm already using

with app.app_context():

Here the code:

from flask import Flask
from flask import g
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from flask import make_response
from bson.objectid import ObjectId
from flask import current_app
import sys


app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'restdb'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/crm1'

@app.errorhandler(404)
def not_found(error):
  return make_response(jsonify({'error':'Notfound' }),404)


with app.app_context():
  mongo = PyMongo(app)
  star = mongo.db.accounts
  output = []
  for s in star.find():
    output.append({'id': str(s['_id']) ,'firstname' : s['firstname'], 'lastname' : s['lastname']})
  print (jsonify({'result' : output}))
  #print ( output)  



if __name__ == '__main__':
    app.run(debug=True)
stackdave
  • 6,655
  • 9
  • 37
  • 56

1 Answers1

2

Jsonify Works with HttpResponse. You can use python json module and print the output Like:

import json

print(json.dumps(output))
Atul Mishra
  • 298
  • 2
  • 11