PythonAnywhere Forums

Internal Server Error

I am repeatedly getting the following error when I am trying to run my app :

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

My server error log says:

2017-03-18 20:34:42 Sat Mar 18 20:34:42 2017 - received message 1 from emperor
2017-03-18 20:34:42 ...gracefully killing workers...
2017-03-18 20:34:42 Gracefully killing worker 1 (pid: 24012)...
2017-03-18 20:34:43 worker 1 buried after 1 seconds
2017-03-18 20:34:43 uWSGI: GAME OVER (insert coin)
2017-03-18 20:34:43 chdir(): No such file or directory [core/uwsgi.c line 1541]
2017-03-18 20:34:43 VACUUM: unix socket /var/sockets/route2sabya.pythonanywhere.com/socket removed.
2017-03-18 20:34:44 *** Starting uWSGI 2.0.5.1 (64bit) on [Sat Mar 18 20:34:43 2017] ***
2017-03-18 20:34:44 compiled with version: 4.8.4 on 20 February 2017 14:10:30
2017-03-18 20:34:44 os: Linux-3.13.0-109-generic #156-Ubuntu SMP Wed Feb 8 16:09:17 UTC 2017
2017-03-18 20:34:44 nodename: giles-liveweb6
2017-03-18 20:34:44 machine: x86_64
2017-03-18 20:34:44 clock source: unix
2017-03-18 20:34:44 pcre jit disabled
2017-03-18 20:34:44 detected number of CPU cores: 4
2017-03-18 20:34:44 current working directory: /etc/uwsgi/vassals
2017-03-18 20:34:44 detected binary path: /usr/local/bin/uwsgi
2017-03-18 20:34:44 *** dumping internal routing table ***
2017-03-18 20:34:44 [rule: 0] subject: path_info regexp: \.svgz$ action: addheader:Content-Encoding:gzip
2017-03-18 20:34:44 *** end of the internal routing table ***
2017-03-18 20:34:44 using Linux cgroup /mnt/cgroups/cpu/user_types/free with mode 700
2017-03-18 20:34:44 assigned process 24082 to cgroup /mnt/cgroups/cpu/user_types/free/tasks
2017-03-18 20:34:44 using Linux cgroup /mnt/cgroups/cpuacct/domains/route2sabya.pythonanywhere.com with mode 700
2017-03-18 20:34:44 assigned process 24082 to cgroup /mnt/cgroups/cpuacct/domains/route2sabya.pythonanywhere.com/tasks
2017-03-18 20:34:44 using Linux cgroup /mnt/cgroups/memory/domains/route2sabya.pythonanywhere.com with mode 700
2017-03-18 20:34:44 assigned process 24082 to cgroup /mnt/cgroups/memory/domains/route2sabya.pythonanywhere.com/tasks
2017-03-18 20:34:44 uWSGI running as root, you can use --uid/--gid/--chroot options
2017-03-18 20:34:44 chroot() to /mnt/chroots/route2sabya/dangermouse
2017-03-18 20:34:44 setgid() to 60000
2017-03-18 20:34:44 setuid() to 2150621
2017-03-18 20:34:44 limiting number of processes to 15...
2017-03-18 20:34:44 your processes number limit is 15
2017-03-18 20:34:44 your memory page size is 4096 bytes
2017-03-18 20:34:44 detected max file descriptor number: 123456
2017-03-18 20:34:44 building mime-types dictionary from file /etc/mime.types...
2017-03-18 20:34:44 536 entry found
2017-03-18 20:34:44 lock engine: pthread robust mutexes
2017-03-18 20:34:44 thunder lock: disabled (you can enable it with --thunder-lock)
2017-03-18 20:34:44 uwsgi socket 0 bound to UNIX address /var/sockets/route2sabya.pythonanywhere.com/socket fd 7
2017-03-18 20:34:44 Python version: 3.6.0 (default, Jan 13 2017, 00:00:00)  [GCC 4.8.4]
2017-03-18 20:34:44 Set PythonHome to /home/route2sabya/.virtualenvs/UFL
2017-03-18 20:34:44 *** Python threads support is disabled. You can enable it with --enable-threads ***
2017-03-18 20:34:44 Python main interpreter initialized at 0x126d450
2017-03-18 20:34:44 your server socket listen backlog is limited to 100 connections
2017-03-18 20:34:44 your mercy for graceful operations on workers is 60 seconds
2017-03-18 20:34:44 setting request body buffering size to 65536 bytes
2017-03-18 20:34:44 mapped 333952 bytes (326 KB) for 1 cores
2017-03-18 20:34:44 *** Operational MODE: single process ***
2017-03-18 20:34:44 initialized 35 metrics
2017-03-18 20:34:44 WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x126d450 pid: 24082 (default app)
2017-03-18 20:34:44 *** uWSGI is running in multiple interpreter mode ***
2017-03-18 20:34:44 spawned uWSGI master process (pid: 24082)
2017-03-18 20:34:44 spawned uWSGI worker 1 (pid: 24084, cores: 1)
2017-03-18 20:34:44 metrics collector thread started
2017-03-18 20:34:44 spawned 2 offload threads for uWSGI worker 1
2017-03-18 20:34:46 announcing my loyalty to the Emperor...

I am a very new user and I have just learned a very little flask to get started. I checked out a few threads that explain the "Internal Server Error" but couldn't understand how to solve the problem. Maybe it has something to do with my "free beginners account". Can anybody please help me out with the issue.

i think that's the server log, not the error log. what does your error log say?

This is what my error log says:

**2017-03-19 05:42:07,275 :[2017-03-19 05:42:07,267] ERROR in app: Exception on /signup [POST]
2017-03-19 05:42:07,279 :Traceback (most recent call last):
2017-03-19 05:42:07,279 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 988, in __call__
2017-03-19 05:42:07,279 :    return self.registry[key]
2017-03-19 05:42:07,279 :KeyError: 140544694601600
2017-03-19 05:42:07,279 :
2017-03-19 05:42:07,280 :During handling of the above exception, another exception occurred:
2017-03-19 05:42:07,280 :
2017-03-19 05:42:07,280 :Traceback (most recent call last):
2017-03-19 05:42:07,280 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
2017-03-19 05:42:07,280 :    response = self.full_dispatch_request()
2017-03-19 05:42:07,280 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
2017-03-19 05:42:07,280 :    rv = self.handle_user_exception(e)
2017-03-19 05:42:07,281 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
2017-03-19 05:42:07,281 :    reraise(exc_type, exc_value, tb)
2017-03-19 05:42:07,281 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
2017-03-19 05:42:07,281 :    raise value
2017-03-19 05:42:07,281 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
2017-03-19 05:42:07,281 :    rv = self.dispatch_request()
2017-03-19 05:42:07,281 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
2017-03-19 05:42:07,281 :    return self.view_functions[rule.endpoint](**req.view_args)
2017-03-19 05:42:07,282 :  File "/home/route2sabya/UFL-web/partA/routes.py", line 71, in signup
2017-03-19 05:42:07,282 :    if form.validate() == False:
2017-03-19 05:42:07,282 :  File "/home/route2sabya/UFL-web/partA/forms.py", line 28, in validate
2017-03-19 05:42:07,282 :    user  = User.query.filter_by(email = self.email.data.lower()).first()
2017-03-19 05:42:07,282 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 498, in __get__
2017-03-19 05:42:07,282 :    return type.query_class(mapper, session=self.sa.session())
2017-03-19 05:42:07,282 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 78, in __call__
2017-03-19 05:42:07,282 :    return self.registry()
2017-03-19 05:42:07,283 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 990, in __call__
2017-03-19 05:42:07,283 :    return self.registry.setdefault(key, self.createfunc())
2017-03-19 05:42:07,283 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2829, in __call__
2017-03-19 05:42:07,283 :    return self.class_(**local_kw)
2017-03-19 05:42:07,283 :  File "/home/route2sabya/.virtualenvs/UFL/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 144, in __init__
2017-03-19 05:42:07,283 :    track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
2017-03-19 05:42:07,283 :KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'**

It looks to me like self.registry is some part of flask-sqlalchemy configuration and that the configuration it is expecting is not there. Check to make sure that you are correctly configuring flask-sqlalchemy.

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/

My guess is that having your db.init_app in the code section that is not run by PythonAnywhere is probably an issue. runserver.py is never run by PythonAnywhere and the if __name__ == '__main__': section in any file is also not run by PythonAnywhere.

Thanks, Glenn ! I tried to follow you. Also, I made some changes with 'app.app_context()' and I somehow, have it working. Though I still lack the clarity, but I have a starting point now. The support was awesome. Keep it up.

:)