Hey, I followed the error log and tried a few iterations but still no success.
My folder structure is:
UFL-web
├── __init__.py
├── __pycache__
│ └── runserver.cpython-36.pyc
├── partA
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ ├── forms.cpython-36.pyc
│ │ ├── models.cpython-36.pyc
│ │ └── routes.cpython-36.pyc
│ ├── forms.py
│ ├── models.py
│ ├── routes.py
│ ├── static
│ │
│ └── templates
│ ├── about.html
│ ├── contact-.html
│ ├── contact.html
│ ├── home-.html
│ ├── layout.html
│ ├── profile-changed.html
│ ├── profile.html
│ ├── signin.html
│ └── signup.html
└── runserver.py
My current error log says:
2017-03-21 06:48:16,242 :[2017-03-21 06:48:16,227] ERROR in app: Exception on /signin [POST]
2017-03-21 06:48:16,253 :Traceback (most recent call last):
2017-03-21 06:48:16,254 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 988, in __call__
2017-03-21 06:48:16,254 : return self.registry[key]
2017-03-21 06:48:16,254 :KeyError: 140578236671872
2017-03-21 06:48:16,254 :
2017-03-21 06:48:16,254 :During handling of the above exception, another exception occurred:
2017-03-21 06:48:16,254 :
2017-03-21 06:48:16,254 :Traceback (most recent call last):
2017-03-21 06:48:16,254 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
2017-03-21 06:48:16,255 : response = self.full_dispatch_request()
2017-03-21 06:48:16,255 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
2017-03-21 06:48:16,255 : rv = self.handle_user_exception(e)
2017-03-21 06:48:16,255 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
2017-03-21 06:48:16,255 : reraise(exc_type, exc_value, tb)
2017-03-21 06:48:16,255 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
2017-03-21 06:48:16,255 : raise value
2017-03-21 06:48:16,256 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
2017-03-21 06:48:16,256 : rv = self.dispatch_request()
2017-03-21 06:48:16,256 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
2017-03-21 06:48:16,256 : return self.view_functions[rule.endpoint](**req.view_args)
2017-03-21 06:48:16,256 : File "/home/route2sabya/UFL-web/partA/routes.py", line 108, in signin
2017-03-21 06:48:16,256 : if form.validate() == False:
2017-03-21 06:48:16,256 : File "/home/route2sabya/UFL-web/partA/forms.py", line 50, in validate
2017-03-21 06:48:16,256 : user = User.query.filter_by(email = self.email.data.lower()).first()
2017-03-21 06:48:16,257 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 498, in __get__
2017-03-21 06:48:16,257 : return type.query_class(mapper, session=self.sa.session())
2017-03-21 06:48:16,257 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 78, in __call__
2017-03-21 06:48:16,258 : return self.registry()
2017-03-21 06:48:16,258 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 990, in __call__
2017-03-21 06:48:16,259 : return self.registry.setdefault(key, self.createfunc())
2017-03-21 06:48:16,259 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2829, in __call__
2017-03-21 06:48:16,259 : return self.class_(**local_kw)
2017-03-21 06:48:16,259 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 145, in __init__
2017-03-21 06:48:16,259 : bind = options.pop('bind', None) or db.engine
2017-03-21 06:48:16,259 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 922, in engine
2017-03-21 06:48:16,259 : return self.get_engine()
2017-03-21 06:48:16,259 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 932, in get_engine
2017-03-21 06:48:16,259 : state = get_state(app)
2017-03-21 06:48:16,259 : File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 611, in get_state
2017-03-21 06:48:16,260 : 'The sqlalchemy extension was not registered to the current ' \
2017-03-21 06:48:16,260 :AssertionError: The sqlalchemy extension was not registered to the current application. Please make sure to call init_app() first.
I am also putting up my other files now.
models.py
from flask_sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
uid = db.Column(db.Integer, primary_key = True)
firstname = db.Column(db.String(100))
lastname = db.Column(db.String(100))
email = db.Column(db.String(120), unique=True)
pwdhash = db.Column(db.String(54))
def __init__(self, firstname, lastname, email, password):
self.firstname = firstname.title()
self.lastname = lastname.title()
self.email = email.lower()
self.set_password(password)
def set_password(self, password):
self.pwdhash = generate_password_hash(password)
return ''
def check_password(self, password):
return check_password_hash(self.pwdhash, password)
init.py
from flask import Flask
import jinja2
app = Flask(__name__, template_folder='templates')
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
username="myDBusername",
password="myDBpassword",
hostname="route2sabya.mysql.pythonanywhere-services.com",
databasename="route2sabya$development",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'mySecretKey'
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = 'myEmailId'
app.config["MAIL_PASSWORD"] = 'myPassword'
from partA.models import db
from partA.routes import mail
mail.init_app(app)
routes.py
from partA import app
from flask import Flask, render_template, request,flash, session, redirect,url_for, g
from partA.forms import ContactForm, SignupForm, SigninForm
from flask_mail import Mail, Message
import jinja2
from partA.models import db,User
from functools import wraps
my_loader = jinja2.ChoiceLoader([
app.jinja_loader,
jinja2.FileSystemLoader('\flask-app\app\partA\templates'),
])
app.jinja_loader = my_loader
mail = Mail()
@app.route('/')
def home():
return redirect(url_for('signin'))
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact', methods=['GET','POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate() ==False:
flash('All fields required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact@example.com', recipients=['route2sabya@gmail.com'])
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)
return render_template('contact.html', success=True)
elif request.method == 'GET':
return render_template('contact.html', form=form)
"""
@app.route('/testdb')
def testdb():
if db.session.query("1").from_statement("SELECT 1").all():
return 'It works.'
else:
return 'something is broken.'
"""
@app.route('/signup', methods = ['GET', 'POST'])
def signup():
form = SignupForm()
if request.method == 'POST':
if form.validate() == False:
flash("All fields required.")
return render_template('signup.html',form=form)
else:
newuser = User(form.firstname.data, form.lastname.data, form.email.data, form.password.data)
db.session.add(newuser)
db.session.commit()
session['email'] = newuser.email
return redirect(url_for('profile'))
#return "[1] Create a new user [2] sign in theb user [3] redirect to the user's profile"
elif request.method == 'GET':
return render_template('signup.html', form=form)
@app.route('/profile')
#@login_required
def profile():
if 'email' not in session:
return redirect(url_for('signin'))
else:
return render_template('profile.html')
@app.route('/signin', methods = ['GET','POST'])
def signin():
form = SigninForm()
if request.method == 'POST':
if form.validate() == False:
#flash('username or password is invalid','error')
return render_template('signin.html', form=form)
else:
#if 'email' in session:
#return redirect(url_for('profile'))
#else:
session['email'] = form.email.data
return redirect(url_for('profile'))
elif request.method == 'GET':
return render_template('signin.html',form=form)
@app.route('/signout', methods=['GET','POST'])
#@login_required
def signout():
if 'email' not in session:
return redirect(url_for('signin'))
session.pop('email',None)
return redirect(url_for('contact'))
forms.py
from flask_wtf import Form
from wtforms import TextField, TextAreaField, SubmitField, validators, PasswordField
from partA.models import db, User
class ContactForm(Form):
name = TextField("Name", [validators.Required("Please enter your name")])
email= TextField("Email",[validators.Required("Please enter your email address"), validators.Email("Please enter your email address")])
subject = TextField("Subject", [validators.Required("Please enter a subject")])
message = TextAreaField("Message", [validators.Required("Please enter a message")])
submit = SubmitField("Send")
class SignupForm(Form):
firstname = TextField("First name", [validators.Required("Please enter your first name.")])
lastname = TextField("Last name",[validators.Required("Please enter your last name.")])
email = TextField("Email", [validators.Required("Please enter your email address"), validators.Email("Please enter your email address.")])
password = PasswordField("Password",[validators.Required("Please enter a password")])
submit = SubmitField("Create account")
def __init__(self, *args,**kw):
Form.__init__(self, *args, **kw)
def validate(self):
if not Form.validate(self):
return False
user = User.query.filter_by(email = self.email.data.lower()).first()
if user:
self.email.errors.append("That email is already taken.")
return False
else:
return ''
class SigninForm(Form):
email = TextField("Email",[validators.Required("Please enter your registered email address"), validators.Email("Please enter your registered email address")])
password = PasswordField("Password",[validators.Required("Please enter your password")])
submit = SubmitField("Sign In")
def __init__(self, *args, **kw):
Form.__init__(self, *args,**kw)
def validate(self):
if not Form.validate(self):
return False
user = User.query.filter_by(email = self.email.data.lower()).first()
if (user != None) and (user.check_password(self.password.data)== True):
return 'OK'
else:
self.email.errors.append("Invalid e-mail or password")
return False
runserver.py
from partA import app
from partA.models import db
if __name__ == '__main__':
db.init_app(app)
app.run()
Please give me some clue as to what is going wrong. I can't figure out how to deal with the registry.
Any lead kind of lead would be very helpful.
This is the link : http://route2sabya.pythonanywhere.com/