I am trying to use flask-restful and mongodb to set up a restful api. I first tried to import mongo from my flask app and use mongo directly, but it cames out with such error:
RuntimeError: working outside of application context
Then I searched and finded out that database should be used in an app context.
So I added context around wherever mongo is used, Below is my dir and code:
├── app
│ ├── __init__.py
│ └── resource
│ ├── api.py
│ ├── __init__.py
├── runserver.py
├── settings.py
app/__init__.py
:
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask('myapp')
# ext pymongo
mongo = PyMongo(app)
from app.resource import api
api.init_app(app)
resource/api.py
:
from app import app, mongo
class Comment(Resource):
parser = reqparse.RequestParser()
parser.add_argument('comment', type=str)
parser.add_argument('community', type=str)
def get(self, id):
# add context
with app.app_context():
res = mongo.db.comment.find_one({'_id': ObjectId(id)})
if res:
res = jsonify(
comment=res['comment'],
community=res['community'])
return res
This code works fine. But I must write with app.app_context():
everytime I use mongo, is there any way to use mongo and avoid writing app.app_context()
?