SQLAchemy 'No application found. Either work inside a view function or push'

旧时模样 提交于 2019-12-11 18:28:21

问题


Ello ello,

I found similar questions on the bug i'm facing, and tried the solutions offered but it didn't work for me.

I'm trying to separate out my models in a different directory and import them into the app.py

When I try to import the db into the python terminal, i'm getting the no application found.

app.py code

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)

models

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

my file directory looks like

Main_app

  • Models
    • Todo.py
  • routes
    • some routes
  • app.py

回答1:


It is ok to have db initialised in 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)

Then in your 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



回答2:


I get a same err that err reason for just can operation db in viewfunc

def __init__(self, id, data):
        self.id = id
        self.data = data

try move that code operation to your viewfunc




回答3:


Flask-SQLAlchemy needs an active application context.

Try:

with app.app_context():
    print(Todo.query.count())

From the flask documentation:

Purpose of the Context

The Flask application object has attributes, such as config, that are useful to access within views and CLI commands. However, importing the app instance within the modules in your project is prone to circular import issues. When using the app factory pattern or writing reusable blueprints or extensions there won’t be an app instance to import at all.

Flask solves this issue with the application context. Rather than referring to an app directly, you use the the current_app proxy, which points to the application handling the current activity.

Flask automatically pushes an application context when handling a request. View functions, error handlers, and other functions that run during a request will have access to current_app.



来源:https://stackoverflow.com/questions/49089584/sqlachemy-no-application-found-either-work-inside-a-view-function-or-push

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