Marvin The Martian
Marvin The Martian

Reputation: 123

No application found on Flask function

I have two file one for the DB model and the other is the main file. The creat_admin_user function does not work. When I try to run init.py I get "No application found. Either work inside a view function or push an application context". I have looked at the SQLAlchemy site and I have the db.init_app line and returning the app object. Not sure what else I am missing. The error appears to be on the user query which is the first line of the create_admin_user function.

--------------- __init__.py ---------------
from .models import User, Note, db, DB_NAME
from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)
    create_database(app)
    
    # create Admin user
    create_admin_user()

    return app
 
def create_database(app):
    if not path.exists('website/' + DB_NAME):
        db.create_all(app=app)
        print('Created Database!')
 
def create_admin_user():

    user = User.query.filter_by(username='admin').first()
    print("after query")

    if user:
        print("User already exists")
    else:
        # Add user to DB
        add_user = User(first_name='LocalAdmin', username='admin', password=generate_password_hash(gen_password,
                                                                                                   method='sha256'))
        # adds user and commits the db.session.add(add_user)
        db.session.commit()
        print(f"Admin user created successfully")
        
--------------- Models.py ---------------

import datetime
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func

db = SQLAlchemy()
DB_NAME = "database.db"


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(100))
    last_name = db.Column(db.String(100))
    email = db.Column(db.String(100))
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(100))
    domain = db.Column(db.String(100), nullable=False)
    creation_date = db.Column(db.DateTime, default=datetime.datetime.now())
    last_login = db.Column(db.DateTime, onupdate=datetime.datetime.now())
    failed_login = db.Column(db.Integer)
    active = db.Column(db.Integer, default=1)

Upvotes: 0

Views: 482

Answers (2)

Marvin The Martian
Marvin The Martian

Reputation: 123

Got it working. I added app.app_context().push() right before calling the create_admin function and it is working correctly now.

Upvotes: 1

Kevin
Kevin

Reputation: 855

If you want to run functions which alters the Database of an Flask Application without starting the Flask Application you have to push the Application Context first.

So you have to call something like this:

self.app = create_app()
self.app_context = self.app.app_context()
self.app_context.push()

And don't forget to remove the context afterwords.

self.app_context.pop()

Upvotes: 0

Related Questions