问题
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