3

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() ?

Community
  • 1
  • 1
sofx
  • 171
  • 1
  • 8

1 Answers1

0

The part you are missing from the question you linked to is this:

...the management of the application context is already handled by Flask when the application is handling a request, but since the create_all() method is NOT run during a view, Flask didn't set up the context for you.

I'm going to modify that answer to hopefully make it more clear.

You only need to use the with app.app_context() code when your code is not already been assigned an app context (for example, when you try to run code directly from a script). In the resource/api.py code sample you have provided, your get method is being called with the app context already set up. It was set up when Flask started handling the request, and will still be set up as Flask hands off control to Flask-RESTful, and thus still be set up when Flask-RESTful hands off control to your get method.

Therefore, you shouldn't need to use app.app_context() in this case.

Community
  • 1
  • 1
Mark Hildreth
  • 42,023
  • 11
  • 120
  • 109