Flask-PyMongo-init_app()缺少1个必需的位置参数:“ app”

时间:2018-09-29 12:19:04

标签: python flask pymongo flask-restful flask-pymongo

我正在尝试使用flask-pymongo初始化我的数据库。

但是我收到以下错误消息,

  

文件“ run.py”,第22行,在
  app = create_app(“ config”)
  create_app中第11行的文件“ run.py”
  mongo.init_app(app)
  TypeError:init_app()缺少1个必需的位置参数:“ 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

我希望他们将mongo导入此资源,以便我可以访问用户集合。

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

我正在尝试使用Flask-restful和flask-pymongo用资源设置一个Restful api。欢迎提出其他改进我的方法的建议。

2 个答案:

答案 0 :(得分:1)

您没有在db.py中实例化PyMongo类。

mongo = PyMongo()

答案 1 :(得分:0)

您应使用this之类的flask-pymongo:

from flask import Flask
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
mongo = PyMongo(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) # 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)