flask NoAppException but flask run works - flask

I have the following structure:
app_dir/
| myapi/
| __init__.py
| myapi_app.py
where myapi_app.py is
from myapi import create_app, db
app = create_app()
and myapi/__init__.py is
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from myapi.config import Config
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
...
return app
When I set FLASK_APP=myapi_app.py and run flask run from the app_dir directory, the flask service starts. However, when I make a request, I get the following error: flask.cli.NoAppException: Could not import "myapi_app". Where am I going wrong?

Your problem is that you are setting $FLASK_APP to the file in which the app variable is stored, you should instead set it to the python object path, e.g.
FLASK_APP=myapi_app:app
However, this is not necessary, as you could also just do:
FLASK_APP=myapi
as Flask will look for a create_app function in the package on its own.

Related

How to determine flask_app name

Sorry if this is a bit basic but wanted to validate what my flask_app name would be that I set in my .env file when running locally.
I run my app using a wsgi.py file in root with the following contents:
from app import create_app, db
application = create_app()
if __name__ == '__main__':
application.run()
However I then have a app/init.py
import os
from config import Config
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
#not sure if i mucked this up
db.init_app(app)
from app.main import main_blueprint
app.register_blueprint(main_blueprint)
return app
Which I run with flask run. Therefore is my app name “app” or “application” or even something else?
You want flask_app variable to be the name of the file which runs the app, so for you in your .env file it looks like you should have:
FLASK_APP = run.py
where run.py is the name of the file containing the first block of code in your question, assuming that your .env file is also in your root folder, let me know if that helps.

Flask - How to load database with config from Flask config?

My folder structure is the following:
- app.py
app
- __init__.py
- database.py
in app.py I have:
from app import create_app
app = create_app()
my init.py looks something like:
from flask import Flask
from app.database import db_session, init_db
db = SQLAlchemy()
def create_app():
myapp = Flask(__name__, static_folder='static', static_url_path='/static', template_folder="templates")
myapp.config.from_object('config.Config')
db.init_app(myapp)
migrate.init_app(myapp, db)
# loading blueprints
from app.core_bp import core_bp
myapp.register_blueprint(core_bp, url_prefix='/', template_folder="templates")
return myapp
and database.py looks like this
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///rapporteur.db')
db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine))
That sqlite path is currently hardcoded to raporteur.db but it should be loaded from config, because I don't want it hardcoded, but unfortunately the flask app is not yet loaded. So how would I do this?
You can use flask-sqlalchemy and set the SQLALCHEMY_DATABASE_URI in the config file.
class Config:
SQLALCHEMY_DATABASE_URI = 'sqlite:///rapporteur.db'
then in your init.py
from youApp import Config
def create_app(config_class=Config)
app = Flask(__name__)
app.config.from_object(config_class)
db = SQLAlchemy()
db.init_app(app)
return app

Flask csrf: key is missing with Blueprint

Hello everyone I have this issue I am not able to correct:
KeyError: 'A secret key is required to use CSRF.'
I am now using Flask with Blueprint.
I am not using CSRF at all but I think the LoginForm is.
I structured my project with Blueprint.
Before that, everything was find.
Here is my init.py file:
from flask import Flask
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.config import Config
from flask_wtf.csrf import CSRFProtect
db = SQLAlchemy()
migrate = Migrate(db)
bcrypt = Bcrypt()
csrf = CSRFProtect()
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.login_message_category = "info"
from Flask import models
from Flask.models import User
admin = Admin(name='Admin')
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
admin.init_app(app)
db.init_app(app)
csrf.init_app(app)
login_manager.init_app(app)
migrate.init_app(app)
bcrypt.init_app(app)
db.init_app(app)
from Flask.users.routes import users
app.register_blueprint(users)
return app
This is my config.py file:
import os
class Config:
SECRET_KEY = "ef2006629e09b70e55a6fb95c4e3a538"
SQLALCHEMY_DATABASE_URI = "sqlite:///site.db"
# WTF_CSRF_SECRET_KEY= "bjk567nvhbvj63vg363vghvghv3768vgfbkijvr784"
# CSRF_ENABLED = True
Thank you for your help !
You should create a SECRET_KEY=<Your secret key here> property in your configuration. It must be a difficult string.
I found the problem
I was not calling properly my config.py file
In my init.py file I change the line:
from flask.config import Config
with the line:
from Flask.config import Config
Flask is the name of my file, which is different from flask.
I should have found another name

Flask - Attempted relative import in non-package

Following this tutorial on how to structure a Flask app, I have:
project/
__init__.py
app.py
models/
__init__.py
base.py
base.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
models/__init__.py
from .base import db
def init_app(app):
db.init_app(app)
project/__init__.py
from flask import Flask
def create_app()
from . import models, routes, services
app = Flask(__name__)
models.init_app(app)
# routes.init_app(app)
# services.init_app(app)
return app
finally, in app.py, I try to run it:
from . import create_app
app = create_app()
if __name__ == '__main__':
app.run(use_reloader=True, threaded=True, debug=True)
but I'm getting the error:
from . import create_app
ValueError: Attempted relative import in non-package
Am I building it right, what am I doing wrong?
I guess you are running your program by:
python project/app.py
In this case, you are not treat your "project" as a python package, which will raise the error you got. Instead, you can run your project with:
FLASK_APP=project.app flask run

python flask ImportError: No module named views.login

I have a app named flaskr. When I want to import views.login` from views. it gives me error:
File "C:\Projects\flaskr\flaskr.py", line 28, in <module>
from flaskr.views.login import login
ImportError: No module named views.login
Before I put all the methods inside the flaskr.py file. I want to move each functions to different views, like login, show_entries, log_out, just like MVC has different views.
flaskr.py
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import os
app = Flask(__name__)
app.config.from_object(__name__)
from flaskr.views.login import login
app.register_blueprint(login)
if __name__ == '__main__':
app.run(debug = True)
login.py
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from jinja2 import TemplateNotFound
login = Blueprint('login', __name__,template_folder='../template')
#app.route('/login')
def login():
return render_template('login.html')
Create folder named app or whatever.
Create __init__.py file in app:
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import os
app = Flask(__name__)
app.config.from_object(__name__)
from app import views
app.register_blueprint(views.login)
Move app.run method into separate start.py file in root directory
from app import app
if __name__ == '__main__':
app.run(debug = True)
Create folder views in app/. Create __init__.py in views
Now you could have structure like this:
your_project_name/
|app/
|__init__.py
|views/
|__init__.py
|login.py
start.py
Sorry, if there are have mistakes.