Flask-PyMongo - init_app() missing 1 required positional argument: 'app'

假如想象 提交于 2019-12-26 05:39:13

问题


i am trying to initialise my db using flask-pymongo.

But i get the following error,

File "run.py", line 22, in
app = create_app("config")
File "run.py", line 11, in create_app
mongo.init_app(app)
TypeError: init_app() missing 1 required positional argument: 'app'

run.py

from flask import Flask
from app import api_bp
from db import mongo

def create_app(config_filename):

    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.register_blueprint(api_bp, url_prefix='/api')

    mongo.init_app(app)

    return app

# def logger():


# def database():


if __name__ == "__main__":
    app = create_app("config")
    app.run(host='0.0.0.0', port=8080, debug=True)

db.py

from flask_pymongo import PyMongo

mongo = PyMongo

config.py

DEBUG = True
SECRET_KEY = "secret"
MONGO_URI = "mongodb://localhost:27017/api"

app/__init__.py

import os
import json
import datetime
from flask import Blueprint
from flask import jsonify
from flask_restful import Api
from .users.resource import UsersResource

api_bp = Blueprint('api', __name__)
api = Api(api_bp)


api.add_resource(UsersResource, '/users')

app/users/resource.py

I want to them import the mongo to this resource so i can access the users collection.

from flask_restful import Resource
from flask import jsonify
from .repository import UsersRepository

class UsersResource(Resource):

    def __init__(self):

        self.repository = UsersRepository()

    def get(self):

        data = {"Users": "Resource"}
        res = data, 200
        return res

I am trying to setup a restful api with resources using Flask-restful and flask-pymongo. Any other suggestions to improve my approach is welcome.


回答1:


You didn't instantiate the PyMongo class in db.py.

mongo = PyMongo()



回答2:


You should use flask-pymongo like this:

from flask import Flask
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
mongo = PyMongo(app)

So in run.py, you should use this code:

from flask import Flask
from app import api_bp
from db import mongo

def create_app(config_filename):

    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.register_blueprint(api_bp, url_prefix='/api')

    # mongo.init_app(app) # remove this line

    return app

# def logger():


# def database():


if __name__ == "__main__":
    app = create_app("config")
    py_mongo = mongo(app)
    app.run(host='0.0.0.0', port=8080, debug=True)


来源:https://stackoverflow.com/questions/52568304/flask-pymongo-init-app-missing-1-required-positional-argument-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!