简体   繁体   中英

Flask-PyMongo with application factory and blueprints

I am trying to implement Flask-PyMongo with blueprints and an application factory and keep getting AttributeError: 'Flask' object has no attribute 'db' My directory structure looks like

myapp/
   myapp.py
   config.py
   /app
       __init__.py
       /v1
             __init__.py
             endpoints.py

In my python script that starts the Flask app I have:

import os
from app import create_app

app = create_app('dev')

In my top level init .py I have:

mongo = PyMongo()

def create_app(config_name):
    app = Flask(__name__)
    mongo.init_app(app)
    app.config.from_object(config[config_name])

    from app.v1 import psapi as psapi_bp
    app.register_blueprint(psapi_bp, url_prefix='/api')

    if not os.path.exists('logs'):
        os.mkdir('logs')

In my endpoints.py I have a route that looks like

@myapp.route('/addentry', methods=['POST'])
def addentry():
    username = request.json['username']
    userid = current_app.db.user_entry.insert({'username':username})
    return jsonify({'userid':userid})

I feel like there is something small that I am missing but I am not seeing it.

您需要在mongo对象上调用db ,而不是在app对象上

to those who may be facing this problem again :

  • you should first define mongo oustside create_app to have access to it from inside other files.
  • then init_app with that like the following:

from flask import Flask, current_app

from flask_pymongo import PyMongo

mongo = PyMongo()

def create_app(config_name):
    app = Flask(__name__, instance_relative_config=False)

    app.config.from_object(app_config[config_name])

    # INIT EXTENSIONS ----------------------

    mongo.init_app(app)

    return app

then in any file you can import mongo from above file. for example:

from ../factory import mongo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM