0

I trying to create a system with models that can be used within the flask's app context and by external jobs. I have created a database.py with the following:

from sqlalchemy import MetaData, Column, Integer, String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base

metadata = MetaData()
Base = declarative_base(metadata=metadata)


class Stock(Base):
    __tablename__ = 'Stock'
    id = Column(Integer, primary_key=True)
    ticker = Column(String(10), nullable=False)
    time_stamp = Column(DateTime, nullable=False)
    open = Column(Float, nullable=False)
    high = Column(Float, nullable=False)
    low = Column(Float, nullable=False)
    close = Column(Float, nullable=False)
    volume = Column(Integer, nullable=False)
    price = Column(Float, nullable=True)

I have also then created a flask_db.py file:

from flask_sqlalchemy import SQLAlchemy

from database import metadata

db = SQLAlchemy(metadata=metadata) 

This is then used in my app.py

from flask import Flask, render_template
from flask_db import db
import os

# create the flask app
app = Flask(__name__, template_folder="dist/", static_folder="dist/", static_url_path="")

# config
app.config.from_object(os.environ['APP_SETTINGS'])

# initialise db
db.init_app(app)


@app.route("/")
def index():
    """
    renders basic index page
    :return: template
    """
    return render_template("index.html")


# app entry point
if __name__ == "__main__":
    app.run()

When I run a file called create_db.py:

from flask_db import db
db.create_all()

I get the following error:

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

I am not really sure why no application is found.

1 Answer 1

1

The db extension will only get initialized when init_app is called, and the app context will only get created when the app is run. But because you're importing from your flask_db module, neither of those things happens - the code in the app module never gets run by the Python interpreter.

What you probably need to do is something like this:

from app import app, db

app_ctx = app.app_context()
ctx.push()
db.create_all()
ctx.pop()

I would think that should work. But I strongly suggest you look into using the application factory pattern to create your app, and using click commands (with the with_appcontext decorator) to add to Flask's cli interface, instead of using one-off scripts. Also, it's probably worth using Flask-Migrate for proper database migrations.

EDIT: in your app module, you probably also need to tell Flask-SQLAlchemy about your custom base model:

db = SQLAlchemy(metadata=metadata, model_class=Base)
Sign up to request clarification or add additional context in comments.

1 Comment

That works! Thanks :). I am looking into the factory pattern as my application is now becoming a bit of a mess!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.