I'm running Flask through thescript, below (run.py)
#!flask/bin/python
from app import app
app.run(debug=True)
When running the script, I have this traceback
File "./run.py", line 2, in <module>
from app import app
File "/home/andy.kwok/microblog/app/__init__.py", line 11, in <module>
lm.init_app(app)
NameError: name 'app' is not defined
I've tried to add from app import app into models.py and models.py but it does not work.
What am I doing wrong?
My __init__.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import basedir
lm= LoginManager()
lm.init_app(app)
oid = OpenID(app,os.path.join(basedir,'tmp'))
lm.login_view = 'login'
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
My models.py
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
try:
return unicode(self.id) # python 2
except NameError:
return str(self.id) # python 3
def __repr__(self):
return '<User %r>' % (self.nickname)
My views.py
from flask import render_template, flash, redirect, session, url_for, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app
from app import db
from app import lm
from app import oid
from .forms import LoginForm
from .models import User
#app.route('/')
#app.route('/index')
#login_required
def index():
user = g.user
posts = [
{
'author': {'nickname': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'nickname': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
return render_template('index.html',
title='Home',
user=user,
posts=posts)
#app.route('/login', methods=['GET', 'POST'])
#oid.loginhandler
def login():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
session['remember_me'] = form.remember_me.data
return oid.try_login(form.openid.data, ask_for=['nickname', 'email'])
return render_template('login.html',
title='Sign In',
form=form,
providers=app.config['OPENID_PROVIDERS'])
#lm.user_loader
def load_user(id):
return User.query.get(int(id))
#oid.after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash('Invalid login. Please try again.')
return redirect(url_for('login'))
user = User.query.filter_by(email=resp.email).first()
if user is None:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('#')[0]
user = User(nickname=nickname, email=resp.email)
db.session.add(user)
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('index'))
#app.before_request
def before_request():
g.user= current_user
You are using the app before importing it, here lm.init_app(app), app is not defined yet.
It should look like this:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import basedir
app = Flask(__name__)
app.config.from_object('config')
lm= LoginManager()
lm.init_app(app)
oid = OpenID(app,os.path.join(basedir,'tmp'))
lm.login_view = 'login'
db = SQLAlchemy(app)
from app import views, models
This error is because of you are not defining app and directly using app
Solution is add this line in your code : app Flask(__name__)
Example: app.py
from flask import Flask
#You need to use following line [app Flask(__name__]
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World with flask"
if __name__ == '__main__':
app.run(port=5000,debug=True)
This should work:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "Hello from homepage!"
if __name__ == '__main__':
app.run()
Related
I am trying to build a web app with login and signup in the nav-bar/header. When I open the web app using index.html, the login and signup option shows at the top (in nav-bar) but when I do python -m flask run, it never shows that login/signup option. I will attach a snippet of my app.py
from distutils.log import debug
from operator import imod
from pickle import FALSE
import re
from flask import Flask,render_template,url_for,redirect,flash,request
from flask_sqlalchemy import SQLAlchemy
import os
from flask_login import LoginManager,login_user,login_required,logout_user,current_user
from flask_migrate import Migrate
from forms import RegistrationForm,LoginForm
from models import User
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
#* ATTACHING DATABASE TO PROJECT FOR USER CREATION
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#* ENCRYPTING THE PASSWORD text
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
# GENERATING SECRET-KEY
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
# CREATING THE MIGRATIONS
migrate = Migrate(app, db)
# login Manager
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)
#login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#app.route('/',methods=['GET'])
def index():
return render_template("index.html",user=current_user)
#app.route('/how_to_play')
#login_required
def how_to_play():
return render_template("how_to_play.html")
#app.route('/play')
def play():
return render_template("play.html")
#app.route('/register', methods = ['POST','GET'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password1.data).decode('utf-8')
user = User(username =form.username.data, email = form.email.data,password=hashed_password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
return render_template('registration/registration.html', form=form)
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
return render_template("index.html",user=current_user)
flash('Invalid email address or Password.')
return render_template('registration/login.html', form=form)
#app.route("/logout")
def logout():
logout_user()
return render_template("index.html",user=current_user)
#app.route('/share/score/', methods = ['GET'])
def share_score():
return render_template('share_score.html')
if __name__ == "__main__":
app.run(debug=True)
Not sure where I am going wrong. Any idea would be appreciated.
Because Flask template doesn't load navbar. Route in Flask doesn't work like route in HTML. In HTML we only need add route like src="/navbar.html", but if the route isn't added in code in Flask, it does not appear when render template.
So you can follow this step https://www.geeksforgeeks.org/navigation-bars-in-flask/
I'm coding a simple flask app and I have already done all the login process. I'm not getting errors but the problem appears when I try to log in, somehow the program doesn't recognize me as a user, although I had already sign up correctly and my user data is in the database. So what ends happening is me trying to access to app_home route and, because it is a login_required route and the login doesn't save my data, I fall into a loop in the login page without being able to do anything.
Here is all the code:
server.py:
from flask import Flask
from flask_mongoengine import MongoEngine
from flask_login import LoginManager
from models import User
app = Flask(__name__)
...
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
#login_manager.user_loader
def load_user(email):
return User.objects(email=email).first()
if __name__ == '__main__':
app.run(debug=True)
models.py:
from flask_login import UserMixin
from mongo_setup import db
class User(UserMixin, db.Document):
email = db.StringField()
password = db.StringField()
auth.py:
from flask import Blueprint, render_template, redirect, url_for, request, flash
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, logout_user, login_required
auth = Blueprint('auth', __name__)
from mongo_setup import db
from models import User
...
#auth.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
user_email = User.objects(email=email).first()
if user_email:
flash("Email address already exists")
return redirect(url_for('auth.signup'))
User(email=email,
password=generate_password_hash(password, method='sha256')
).save()
return render_template('signup.html')
#auth.route('/login')
def login_get():
return render_template('login.html')
#auth.route('/login', methods=['POST'])
def login():
email = request.form.get("email")
password = request.form.get("address")
remember = True if request.form.get('remember') else False
user = User.objects(email=email).first()
if not user or not check_password_hash(user.password, password):
flash('Please check your login details and try again.')
return redirect(url_for('auth.login'))
login_user(user, remember=remember)
return redirect(url_for('auth.app_home'))
#auth.route('/app/<address>/<data>/<delete>', methods=['GET', 'POST'])
#login_required
def app_home(address, data, delete):
return render_template('app.html')
#login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
You need to either change your load_user method to find the User object by id or overload the get_id() method on your User model to match your load_user() method to uniquely identify the user by email.
See: https://flask-login.readthedocs.io/en/latest/#how-it-works
This is my first post on here, glad i reached as this code is whipping my mental energy, enjoying it all the same :) So I'm trying to build the blog project using PyMongo and flash-login, LoginManager, but its just returning errors. I'm following along with the code from Miguel Grinbergs awesome blog videos. I've been scratching my head on this for a few days now and would really appreciate the input. Thanks and Happy Friday
import os
import env
import model
from model import User
from flask_login import LoginManager, current_user, login_user
from flask import Flask, render_template, url_for, flash, redirect
from flask_pymongo import PyMongo
from forms import LoginForm
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
# SSSSHHHH
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
mongo = PyMongo(app)
login = LoginManager(app)
#app.route('/')
def base():
return render_template('base.html')
#app.route('/index')
def home():
return render_template('index.html', title='Home')
#app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
# IF ITS RIGHT THE FIRST TIME
if form.validate_on_submit():
user = User.mongo.db.find_one(username=form.username.data).first_or_404()
if user is None or not user.check_password(form.password.data):
flash(f'Invalid username or password')
return redirect(url_for('home'))
#flash('Login success for user {}, remember_me{}'.format(
#form.username.data, form.remember_me.data))
login_user(user, remember=form.remember_me.data)
return redirect(url_for('home'))
return render_template('login.html', title='Log In', form=form)
if __name__ == '__main__':
app.run(host=os.environ.get('IP'),
port=int(os.environ.get('PORT')),
debug=True)
import os
from mini import login
from flask_login import UserMixin, User
#login.user_loader
def load_user(_id):
return User.mongo.db.find(toInt(_id))
class User(UserMixin, db.Document):
_id = ObjectId (primary_key=True)
username = StringField (unique=True)
email = StringField (unique=True)
password = StringField (default=True)
# REPR TELLS PYTHON HOW TO DEAL WITH OBJECTS OF THIS. CLASS
def __repr__(self):
return '<User {}>'.format(self.username)
In an attempt to run a flask project, which uses both wsgi, nginx in a docker configuration, I am facing the following error:
No user_loader has been installed for this LoginManager. Refer to https://flask-login.readthedocs.io/en/latest/#how-it-works for more info. However, if no login is considered, the system works fine.
How could I solve this?
Some more info:
My system files are as follows:
__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object('instance.config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
flask_bcrypt = Bcrypt(app)
manager = Manager(app)
Code to control the user session:
from instance.config import SECRET_KEY_LOGIN
login_manager = LoginManager(app)
---------------------------------------------------------------------------
login.py
from flask import render_template, request, Blueprint, url_for, redirect
from flask_login import login_user, logout_user, current_user
from app import flask_bcrypt, login_manager
from app.models.login import LoginForm
from app.models.tabelas import Usuario
sign_in = Blueprint('sign_in', __name__)
#login_manager.user_loader
def load_user(id_usuario):
return Usuario.query.filter_by(id_usuario=id_usuario).first()
#login_manager.request_loader
def request_loader(_request):
# print ('using request loader')
# return "load_user_token(_request)"
#sign_in.route('/', methods=['GET', 'POST'])
#sign_in.route('/login', methods=['GET','POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
else:
error = None
form = LoginForm()
if request.method == 'POST':
if form.validate_on_submit():
usuario = Usuario.query.filter_by(ds_email = form.ds_email.data).first()
if usuario and flask_bcrypt.check_password_hash(usuario.ds_password, form.ds_password.data):
login_user(usuario)
return redirect(url_for('home'))
else:
error = 'Invalid Login .'
else:
error = 'Error'
print(form.errors)
return render_template('admin/login.html', form=form, error=error)
Add in your __init__.py this code below the login_manager instance.
#login_manager.user_loader
def load_user(id):
return User.query.filter_by(user_id=id).first()
After that you can delete the #login_manager decorator and its respect function from login.py
I have flask project which work on presently. (below)
When I run this project using command
python run.py
I get following error.
Traceback (most recent call last):
File "run.py", line 1, in
from site import app
ImportError: cannot import name 'app'
run.py
from site import app
import os
app.secret_key = os.urandom(24)
port = int(os.environ.get('PORT', 5000))
if __name__ == '__main__':
app.run(debug="True")
# app.run(host='0.0.0.0', port=port)
__init__.py
from .views import app
from .models import db
db.create_all()
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password#localhost:5432/db'
app.config['SECURITY_REGISTERABLE'] = True
views.py
from flask import Flask
from .models import User, db
from flask import render_template, request, redirect, url_for
from flask.ext.security import login_required
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/profile/<email>')
#login_required
def user_index(email):
user = User.query.filter_by(email=email).first()
return render_template('profile.html', user=user)
#app.route('/post_user', methods=['POST'])
def post_user():
if request.form["action"] == "submit_btn":
user = User(request.form['username'], request.form['email'])
db.session.add(user)
db.session.commit()
return redirect(url_for('index'))
models.py
from flask import Flask
from flask.ext.mail import Mail, Message
from flask_sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin
app = Flask(__name__, static_url_path='')
db = SQLAlchemy(app)
mail = Mail()
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
What should be the directory structure? Also how should I import the models and views in order to make the server work?
Please tell me if you need any other info, thanks in advance.
Rename the site's name so python dont try to import the site standard library, also is better to define the app inside the init.py file: Docs