0

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
Generaldeep
  • 437
  • 2
  • 12
  • 30

4 Answers4

5

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.

codeape
  • 97,830
  • 24
  • 159
  • 188
1

In a nutshell, do something like this:

from yourapp import create_app
app = create_app()
app.app_context().push()
Arshid KV
  • 9,631
  • 3
  • 35
  • 36
0

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
Nour Wolf
  • 2,140
  • 25
  • 24
  • I tried that earlier as well, and I'm getting no errors. However, in python terminal when I run "from app import db" and then "db.create_all()", my table's aren't created in postgres. – Generaldeep Mar 04 '18 at 08:04
  • wait, I got it. I was import db from app, but I should'be done from models.model import db and then run db.create_all() – Generaldeep Mar 04 '18 at 08:06
  • When you import db from app you didn't yet reach the models' declarations. Therefore `db.create_all()` won't create any tables. Check this answer https://stackoverflow.com/a/20749534/552621 – Nour Wolf Mar 04 '18 at 12:23
  • 1
    I'm actually having the circular dependency issue rn. I looked at the thread you linked. I'm able to create the table, but, I cannot retrieve the data in a Get request. My app.py file doesn't recognize the model Task – Generaldeep Mar 05 '18 at 00:56
  • Where are your views located? how are you importing the models? – Nour Wolf Mar 05 '18 at 12:36
  • Hey, forgive my ultra noobness being new to Pythong/Flask, but do I need views if i want to use flask as a REST API? – Generaldeep Mar 05 '18 at 21:16
  • check out this thread for how my models are being imported. https://stackoverflow.com/questions/49102195/flask-sqlalchemy-module-cannot-be-imported-using-circular-dependency – Generaldeep Mar 05 '18 at 21:17
0

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

doit
  • 1