python-3.x - python 3.x SQLAchemy'No application found. Either work inside a view function or push'

当我尝试将数据库导入python终端时,出现错误: no application found.

app.py代码


from flask import Flask


from flask_restful import Resource, Api


# from flask_sqlalchemy import SQLAlchemy


from routes import test, root, user


from models.todo import db



app = Flask(__name__)


api = Api(app)


app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:pass123@localhost/db'


app.config['SECRET_KEY'] = 'thiskeyissecret'


# db.init_app(app)



with app.app_context():


 api = Api(app)


 db.init_app(app)



api.add_resource(root.HelloWorld, '/')


api.add_resource(test.Test, '/test')


api.add_resource(user.User, '/user')



if __name__ == '__main__':


 app.run(debug=True)



模型


from flask_sqlalchemy import SQLAlchemy



db = SQLAlchemy()



class Todo(db.Model):


 __tablename__ = 'Todos'


 id = db.Column('id', db.Integer, primary_key=True)


 data = db.Column('data', db.Unicode)



 def __init__(self, id, data):


 self.id = id


 self.data = data



 def __repr__(self):


 return '<Todo %>' % self.id



时间:

让db在app.py中初始化


from flask import Flask


from flask_restful import Api


from flask_sqlalchemy import SQLAlchemy


from routes import test, root, user



app = Flask(__name__)


api = Api(app)


app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:pass123@localhost/db'


app.config['SECRET_KEY'] = 'thiskeyissecret'


db = SQLAlchemy(app)



api.add_resource(root.HelloWorld, '/')


api.add_resource(test.Test, '/test')


api.add_resource(user.User, '/user')



if __name__ == '__main__':


 app.run(debug=True)



然后在你的todo.py


from app import db



class Todo(db.Model):


 __tablename__ = 'Todos'


 id = db.Column('id', db.Integer, primary_key=True)


 data = db.Column('data', db.Unicode)



 def __init__(self, id, data):


 self.id = id


 self.data = data



 def __repr__(self):


 return '<Todo %>' % self.id



...