I've looked at help guides and so forth but I still cannot seem to get Flask Blueprints working.
Here is my structure
root /
config.py
|app/
| __init__.py
| user_auth/
| __init__.py
| app.py
| routes.py
In the app/init.py file, it is the following
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
from .user_auth.routes import user_auth
app.register_blueprint(user_auth, url_prefix="")
From the user_auth init.py file is
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
app.config['SECRET_KEY'] = 'trial'
from user_auth import routes, models
This is the user_auth/routes.py file
from user_auth import app, db
from flask_login import login_required
from user_auth.forms import RegistrationForm, LoginForm
from flask import request, render_template, flash, redirect, url_for, Blueprint
from werkzeug.urls import url_parse
from flask_login import logout_user
from flask_login import current_user, login_user
from user_auth.models import User
from flask import Blueprint
user_auth = Blueprint('user_auth', __name__)
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html', title='Welcome')
#app.route('/register', methods=["POST", "GET"])
def register():
... (Other paths)
I am running Windows and used the following command
set FLASK_APP=app
I then use
flask run
When I try to run, it says the following:
Error: While importing "app", an ImportError was raised:
Traceback (most recent call last):
File "...\python38-32\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "...\root\app\__init__.py", line 8, in <module>
from .user_auth.routes import user_auth
File "...\root\app\user_auth\__init__.py", line 16, in <module>
from user_auth import routes, models
ModuleNotFoundError: No module named 'user_auth'
Thank you in advance for the help.
For all files in app/user_auth/ like the init.py and routes.py that you mentionned up there, you nede either to access the package with
absolute import : from root.app.user_auth
relative import : from ..user_auth
Then i'd suggest to not use the same name for more than 1 think, here user_auth is both a package name, and the the variable name of you blueprint
Change like
# routes.py
user_auth_bp = Blueprint('user_auth', __name__)
# app/__init__.py
from .user_auth.routes import user_auth_bp
app.register_blueprint(user_auth_bp, url_prefix="")
Related
very confused here. I have a large flask app that I am trying to migrate to our production server, and the app factory always crashes due the error in the title. Here's app/__init__.py:
from flask import Flask, render_template
from app.extensions import db, login_manager, mail
from history import history
from app.jinja_filters import currency
from app.projects import projects
from app.reporting import reporting
from app.requests import requests
from app.user import users
import logging
def create_app(config):
logging.basicConfig(
filename='/<path-to-app-root>/log/por_rm_log.log',
level=logging.DEBUG,
format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s'
)
app = Flask(__name__)
print(f'config is {config}')
if config == 'development':
app.config.from_object('config.DevelopmentConfig')
elif config == 'testing':
app.config.from_object('config.TestingConfig')
elif config == 'production':
app.config.from_object('config.ProductionConfig')
db.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
app.register_blueprint(currency)
app.register_blueprint(history)
app.register_blueprint(projects)
app.register_blueprint(reporting)
app.register_blueprint(requests)
app.register_blueprint(users)
#app.route('/', methods=['GET'])
def index():
return render_template('base.html.jinja')
app.logger.info(f'App restarted ({config})')
return app
Here's the declaration of the projects blueprint in app/projects/views.py:
from distutils.util import strtobool
from flask import Blueprint, jsonify, render_template, request
from .lib import compile_por_counts, get_submarkets
from .models import ProjectOfRecord
from app.extensions import db
from app.requests import ChangeRequestForm
projects = Blueprint('projects', __name__, url_prefix='/projects')
....all my routes for projects...
When I try to start the production server, it doesn't work. Here's the traceback the wsgi_error_log:
File "<path-to-app-root>/app.wsgi", line 10, in <module>
from wsgi import app as application
File "<path-to-app-root>/wsgi.py", line 5, in <module>
app = create_app('production')
File "<path-to-app-root>/__init__.py", line 34, in create_app
NameError: name 'url_prefix' is not defined
I'm stumped here. The blueprints before projects register just fine. TIA!
EDIT: Because Aryan Jain asked, here are the contents of /app/projects/__init__.py:
from .views import projects
from .models import ProjectOfRecord
I'm trying to setup a flask application which runs on Python 3.7.x. I've referenced many tutorials online but can't seem to resolve this ModuleNotFoundError and none of the stackoverflow questions are related.
Below is my project structure:
project/
app/
__init__.py
api.py
conf.py
models.py
schema.py
orders-mgmt.toml
requirements.txt
README.md
# app/__init__.py
from flask import Flask
from flask_restful import Api
from app.conf import load_from_toml
import logging
import os.path
if os.path.isfile('/opt/project/orders-mgmt.toml'):
config = load_from_toml('/opt/project/orders-mgmt.toml')
else:
config = load_from_toml()
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = config['mysql']['db_uri']
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
'pool_recycle': 3000,
'pool_pre_ping': True,
}
# app/api.py
from flask import jsonify
from flask_restful import Resource
from flask_sqlalchemy import SQLAlchemy
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema
db = SQLAlchemy(app)
class TestGet(Resource):
def get(self):
return 'okay'
api.add_resource(TestGet, '/')
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=5000)
I'm getting the ModuleNotFoundError in app/api.py line from app import app, api, config when I run python app/api.py:
$ python app/api.py
Traceback (most recent call last):
File "app/api.py", line 4, in <module>
from app import app, api, config
ModuleNotFoundError: No module named 'app'
May I know what is the issue here with my flask application?
You have circular dependency issue
Your app will not work in such files structure
Remove logic from init module to another one OR you'll need to remove all absolute imports(imports for your own modules) and replace them with relative
for __init__ module
replace this line:
from app.conf import load_from_toml
with
from .conf import load_from_toml
for app module
replace these lines:
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema
with
from . import app, api, config
from .models import Request
from .schema import RequestSchema
I am developing a Flask application, and I am not sure why I am getting this error:
File "app.py", line 17, in <module>
from endpoints.users.resource import UserResource
File "{basedir}/endpoints/users/resource.py", line 4, in <module>
from .model import User
File "{basedir}/endpoints/users/model.py", line 1, in <module>
from app import db
File "{basedir}/app.py", line 17, in <module>
from endpoints.users.resource import UserResource
ImportError: cannot import name 'UserResource' from 'endpoints.users.resource' ({basedir}/endpoints/users/resource.py)
I believe it is due to a circular dependency, from looking at the error, but I can't figure out why, because I think that the order in which I am importing things in my code should have circumvented this issue:
app.py:
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
api = Api(app)
api.prefix = '/api'
from endpoints.users.resource import UserResource
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from app import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from .model import User
from app import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
In app.py, since I am importing from endpoints.users.resource after db is created, shouldn't that circumvent the circular dependency?
In addition, I can run this with flask run but when I try to use python app.py, then it gives me the above error. Why would these give different results?
So on from endpoints.users.resource import UserResource line python tries to import from app import db line to app.py which causes app reference to itself, which is not good at all.
One workaround to solve circual import errors in Flask is using init_app function which exists in most of Flask apps. So just create database file like this:
database.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app.py
from flask import Flask
from flask_restful import Api
from database import db
from endpoints.users.resource import UserResource
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
api = Api(app)
api.prefix = '/api'
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from database import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from endpoints.users.model import User
from database import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
Note that I rewrote your imports from related, so don't forget to add __init__.py files
Your structure will be like this:
.
├── app.py
└── database.py/
└── endpoints/
├── __init__.py
└── users/
├── __init__.py
├── model.py
└── resource.py
I'm trying to turn my Flask code into a python package structure, but now that I've done that, when I try running the code, none of the HTML templates are found.
Here is the simplified structure of my current flask package. run.py is what I use to execute the Flask code. routes.py contains all my #app.routes where the HTML templates are called.
pipeline-ui/
run.py
pipeline_app/
__init__.py
routes.py
models.py
forms.py
templates/
pipeline-alt.html
The error message I get is: TemplateNotFound: pipeline-alt.html
init.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask('__name__')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
from pipeline_app import routes
run.py:
from pipeline_app import app
if __name__ == '__main__':
app.run(debug=True)
routes.py:
from flask import url_for, render_template, request, flash, redirect
from pipeline_app import app
from pipeline_app.forms import InputForm, RegistrationForm, LoginForm
from pipeline_app.models import User, Post
from flask_login import login_user, current_user, logout_user, login_required
from math import ceil
import json
import subprocess
import os
import sys
from pprint import pprint
#app.route('/', methods=['GET', 'POST'])
def pipeline():
form = InputForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
STACK_NAME = request.form['stack_name']
# Store data in database for future use
db.create_all()
db_inputs = Post(stack_name=STACK_NAME)
db.session.add(db_inputs)
db.session.commit()
return render_template('pipeline-alt.html',
title='Pipeline Input',
form=form,
STACK_NAME=STACK_NAME)
Change app = Flask('__name__') to app = Flask(__name__). Flask uses this parameter to find resources on the filesystem, so if it is not set correctly it will not be able to find your templates.
I am wanting to import a class from my __init__ file. But I am unsuccessful in importing it. This is my directory structure
/fitBody_app
/fitBody
/static
/templates
__init__.py
models.py
views.py
run.py
These are all the imports of my __init__.py file:
import os
from flask import Flask
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from wtforms import fields, widgets
from fitBody.views import my_app
from flask_bootstrap import Bootstrap
app = Flask(__name__)
db = SQLAlchemy(app)
These are all my imports in my views.py file:
import bcrypt
from flask import flash, redirect, render_template, request, session, Blueprint, url_for
from fitBody.models import RegistrationForm
from fitBody.models import cursor, conn
from fitBody import db
my_app = Blueprint('fitBody', __name__)
<......>
When I try to run the file, this is my traceback:
Traceback (most recent call last):
File "/Users/kai/github-projects/fitBody_app/run.py", line 1, in <module>
from fitBody import app
File "/Users/kai/github-projects/fitBody_app/fitBody/__init__.py", line 9, in <module>
from fitBody.views import fitBody
File "/Users/kai/github-projects/fitBody_app/fitBody/views.py", line 8, in <module>
from fitBody import db
ImportError: cannot import name 'db'
I had thought that since I am importing from within the same folder that it is possible to just give the import like this.
How would I go about importing the db object from the __init__.py file?
Since views.py use db the import statement should come after db defination. Or for better design move blueprints to another file, and just keep blueprint's in that file:
#__init__.py
app = Flask(__name__)
db = SQLAlchemy(app)
from fitBody.views import my_app
It doesn't have anything to do with importing from an __init__.py file. Your views.py is importing from your __init__.py file, and __init__.py file is importing from your views.py, which is an import cycle. I am not sure how your models.py looks like, but how about you initialize db in models.py and have both __init__.py and views.py import from models.py