Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

share/access db connection #101

Closed
higee opened this issue Jan 27, 2018 · 4 comments
Closed

share/access db connection #101

higee opened this issue Jan 27, 2018 · 4 comments

Comments

@higee
Copy link

higee commented Jan 27, 2018

Hi, I'm quite new to Flask and struggling with flask-pymongo connection with my Flask app. First of all, following is my overall structure. I've simplified so that it would be more readable.

screen shot 2018-01-27 at 5 42 29 pm

I'm trying to create a db connection in main.py and use that db client from test.py under resources. main.py and test.py are as follows.

# main.py
 
from flask import Flask
from flask_restful import Api
from flask_pymongo import PyMongo
from resources.test import Test
 
app = Flask(__name__)
 
api = Api(app)
api.add_resource(Test, '/test')
 
app.config['MONGO_DBNAME'] = ''
app.config['MONGO_URI'] = ''
mongo = PyMongo(app, config_prefix='MONGO')
 
if __name__ == '__main__':
    app.run(port=5000)
#test.py

from flask_restful import Resource, reqparse
 
class User(Resource):
 
    parser = reqparse.RequestParser()
 
    parser.add_argument('name', type=str)
    parser.add_argument('age', type=int)
 
    def post(self):
 
        data = User.parser.parse_args() 
        response  = {
            'name' : data['name'], 
            'age' : data['age']
        }
 
        mongo.db.test_collection.insert_one(response)        
 
        return {'message' : 'successfully inserted'}

There might have been some typos or syntax error while copy and pasting here. But the thing is that Flask app worked fine until started using flask-pymongo. I googled and made some changes but have failed to solve my problem.

Accoring to Quickstart section in flask-pymongo document, it seems like that I could use db directly in views (which in my case would be resources directory). In my case, however, I get NameError saying that 'mongo not defined'.

What would be nice way to access database client from resources/test.py in my case?

@higee
Copy link
Author

higee commented Jan 27, 2018

My current approach is this.

  1. mongo => app.mongo
# main.py
 
from flask import Flask
from flask_restful import Api
from flask_pymongo import PyMongo
from resources.test import Test
 
app = Flask(__name__)
 
api = Api(app)
api.add_resource(Test, '/test')
 
app.config['MONGO_DBNAME'] = ''
app.config['MONGO_URI'] = ''
app.mongo = PyMongo(app, config_prefix='MONGO')
 
if __name__ == '__main__':
    app.run(port=5000)
  1. mongo => current_app.mongo
#test.py

from flask_restful import Resource, reqparse
from flask import current_app
 
class User(Resource):
 
    parser = reqparse.RequestParser()
 
    parser.add_argument('name', type=str)
    parser.add_argument('age', type=int)
 
    def post(self):
 
        data = User.parser.parse_args() 
        response  = {
            'name' : data['name'], 
            'age' : data['age']
        }
 
        current_app.mongo.db.test_collection.insert_one(response)        
 
        return {'message' : 'successfully inserted'}
  1. added a line in uwsgi.ini
lazy-apps: true

It works with above configuration, but not sure how things are working behind the scenes. Most of all, not sure whether this is the right approach to solve this issue.

@dcrosta
Copy link
Owner

dcrosta commented May 19, 2018

A NameError in Python means that you tried to use a variable that Python can't find. In this particular case, it looks like it was because you weren't importing your main module into the test module, so any attempt to use mongo would fail. You can add from main import mongo, or use current_app as you are doing. (There are slight differences between those two -- you can read more about what current_app does on the Flask docs)

@dcrosta
Copy link
Owner

dcrosta commented May 28, 2018

Closing this now, but please update if you still have any questions.

@dcrosta dcrosta closed this as completed May 28, 2018
@higee
Copy link
Author

higee commented Aug 14, 2018

@dcrosta Sorry for delayed reply. Having gone through Flask docs you've attached, I decided to add from main import mongo and it now works the way I expected. I appreciate your time and consideration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants