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.
Related
This question already has answers here:
Flask: How to use app context inside blueprints?
(2 answers)
Closed 8 months ago.
My problem occurs mainly when I try and upload a picture in a separate html form. Before I added the app.config I would successfully get POST and GET requests. On visual code it tells me that app is not defined but I'm not sure how to define it in my image.py file.
This is my image.py file app.config
from unicodedata import category
from flask import Flask, Blueprint, render_template, request, flash, jsonify, url_for, redirect
import urllib.request
from werkzeug.utils import secure_filename
from flask_login import login_required , current_user
from .models import Note
from .import db
import json
import os
image = Blueprint('image', __name__)
#image.route('/', methods=['GET','POST'])
#login_required
def Upload():
if request.method == "POST":
if request.files:
image = request.files["image"]
image.save(os.path.join(app.config['IMAGE_UPLOADS'], image.filename))
print("image saved")
return redirect(request.url)
return render_template("image.html", user=current_user)
My init.py file with my app configurations.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
#Secret key into app
app.config['SECRET_KEY'] = '****'
app.config['IMAGE_UPLOADS'] = r"C:\Users\qw\Desktop\StCh\website\static\Images"
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
and finally my main.py file to run the app.
from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
the error keeps on occurring even after I try and import from website or
I resolved it by just adding
app = Flask(__name__)
into my image.py file. Feel stupid
I tried to use Flask-Dance with normal flask app and it works and if I try to implement with flask blueprints it doesn't work. How to register flask-dance to flask blueprints?
My views.py for auth blueprint
from flask import render_template, url_for, redirect, current_app, request
from app.auth import auth
from flask_dance.contrib import github
#auth.route('/login')
def login():
return render_template('auth/login.html')
#auth.route("/")
def github():
if not github.authorized:
return redirect(url_for("github.login"))
resp = github.get("/user")
assert resp.ok
return "You are #{login} on GitHub".format(login=resp.json()["login"])
my init.py for auth blueprint
from flask import Blueprint
from flask_dance.contrib.github import make_github_blueprint, github
auth = Blueprint('auth', __name__, url_prefix='/auth')
blueprint = make_github_blueprint(client_id="m-client-id",client_secret="my-client-secret")
auth.register_blueprint(blueprint, url_prefix="/auth")
from app.auth import views
and my main init.py file:
from flask import Flask
from flask_fontawesome import FontAwesome
from app.config import Config
fa = FontAwesome()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
fa.init_app(app)
from app.public import public
app.register_blueprint(public)
from app.auth import auth
app.register_blueprint(auth)
return app
First you should create and register different blueprint for github.
github/init.py
from flask_dance.contrib import github
from flask_dance.contrib.github import make_github_blueprint
github_blueprint = make_github_blueprint(client_id='your-client-id',client_secret='your-client-secret')
from app.github import views
github/views.py
#github_blueprint.route("/")
def github_login():
if not github.authorized:
return redirect(url_for('github.login'))
account_info = github.get('/user')
if account_info.ok:
account = account_info.json()
return '<h1>Your Github name is {}'.format(account['login'])
and finally in your main init.py file
from flask import Flask
from flask_fontawesome import FontAwesome
from app.config import Config
fa = FontAwesome()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
fa.init_app(app)
from app.public import public
app.register_blueprint(public)
from app.auth import auth
app.register_blueprint(auth)
from app.github import github_blueprint
app.register_blueprint(github_blueprint, url_prefix='/github_login')
#/github_login=callback url
return app
I am getting the following error when trying to set up a scheduled job for my flask app:
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
I have tried to include the function 'print_session' (which is just a dummy function to check the session data will pull through - in reality this function will query a database) with a 'current_app.appcontext() with loop as I have seen on a few other apps but no joy. Does anyone know why it is still out of the application context?
main.py
from website import create_app
app = create_app()
if __name__=="__main__":
app.run(debug=True,host='localhost',port=5000,threaded=True)
init.py
from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_session import Session
from flask_login import LoginManager
import redis
db = SQLAlchemy()
DB_NAME = 'sqlite:///db.sqlite3'
sess=Session()
login_manager = LoginManager()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = "SECRET_KEY"
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SESSION_TYPE'] = 'SESSION_TYPE'
app.config['SESSION_REDIS'] = 'SESSION_REDIS'
db.init_app(app)
sess.init_app(app)
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
# with app.app_context():
from .views import views
from .auth import auth
app.register_blueprint(views,url_prefix='/')
app.register_blueprint(auth,url_prefix='/')
from .models import User,Token
create_database(app)
return app
def create_database(app):
db.create_all(app=app)
print('Created database')
views.py
from flask import Blueprint,render_template,session,redirect,request,url_for
from flask import current_app
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
from flask_login import login_required,current_user
from requests_oauthlib import OAuth2Session
from . import db
from .models import Token
from functools import wraps
def print_session(value):
with current_app.app_context():
print('Yes',value)
return(redirect(url_for('views.home')))
#views.route('/start_schedule')
#login_required
def start_xero_schedule():
with app.app_context():
sched = BackgroundScheduler()
sched.add_job(print_session,'interval',args=[session['value']],seconds=10)
sched.start()
return(redirect(url_for('views.xero')))
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="")
I want to set up a basic admin interface using flask-admin, and I want all of this to sit in a blueprint. Here's a minimal version my code:
#app.py
from flask import Flask
from bp import bp
app = Flask(__name__)
app.register_blueprint(bp)
if __name__ == "__main__":
app.run(debug=True)
#bp.py
from flask import Blueprint, current_app
from flask_admin import Admin
from flask_admin.contrib.pymongo import ModelView
import pymongo
conn = pymongo.MongoClient()
bp = Blueprint('bp', __name__,
template_folder='templates')
admin = Admin(current_app)
admin.add_view(ModelView(conn.my_db.my_collection))
When running python app.py, it crashes with RuntimeError: working outside of application context, because admin is in no way hooked (or whatever word is used to describe that) to bp.
Normally, one would write
#bp.route('/<page>')
def show(page):
pass
But I can't find the right decorator in the context of creating an Admin object. One thing I tried is to do admin = Admin() in bp.py, import admin in app.py and then admin.app = app in app.py. That works, but it feels like I'm splitting logic in several files, so I'm not really comfortable with that. What's the pythonic way to deal with this situation?
You need the actual app object to init the Flask admin Class. Current_app won't work. This call should be placed on app.py. Then on the blueprint you can use
from app import admin
It work out in this way. just for your reference.
#YourApp/init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
db = SQLAlchemy()
admin = Admin(name='TuozhanOA', template_mode='bootstrap3')
def create_app(config_class=Config):
app = Flask(name)
app.config.from_object(Config)
db.init_app(app)
admin.init_app(app)
from YourApp.main.routes import main
app.register_blueprint(main)
from YourApp.adminbp.routes import adminbp, user_datastore
app.register_blueprint(adminbp)
security = Security(app, user_datastore)
return app
#YourApp/adminbp/routes.py
from flask import render_template, Blueprint
from YourApp.models import User, Role
from YourApp import db, admin
from flask_admin.contrib.sqla import ModelView
from wtforms.fields import PasswordField
from flask_admin.contrib.fileadmin import FileAdmin
import os.path as op
from flask_security import current_user, login_required, RoleMixin, Security,
SQLAlchemyUserDatastore, UserMixin, utils
adminbp = Blueprint('adminbp', name)
admin.add_view(ModelView(User, db.session, category="Team"))
admin.add_view(ModelView(Role, db.session, category="Team"))
path = op.join(op.dirname(file), 'tuozhan')
admin.add_view(FileAdmin(path, '/static/tuozhan/', name='File Explore'))