Forums

Flask: Peewee and SQLite error

Hi, Whenever I try to login or register a user in my app, I come across an error. This must be due to issues with my database or ORM. The database and app runs fine on my local machine. Here are the error logs:

2015-08-19 20:39:43,526 :  File "/bin/user_wsgi_wrapper.py", line 130, in __call__
2015-08-19 20:39:43,527 :    self.error_log_file.logger.exception("Error running WSGI application")
2015-08-19 20:39:43,527 :  File "/usr/lib/python2.7/logging/__init__.py", line 1185, in exception
2015-08-19 20:39:43,527 :    self.error(msg, *args, **kwargs)
2015-08-19 20:39:43,527 :  File "/usr/lib/python2.7/logging/__init__.py", line 1178, in error
2015-08-19 20:39:43,528 :    self._log(ERROR, msg, args, **kwargs)
2015-08-19 20:39:43,528 :  File "/usr/lib/python2.7/logging/__init__.py", line 1270, in _log
2015-08-19 20:39:43,528 :    record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
2015-08-19 20:39:43,528 :  File "/usr/lib/python2.7/logging/__init__.py", line 1244, in makeRecord
2015-08-19 20:39:43,528 :    rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
2015-08-19 20:39:43,529 :  File "/usr/lib/python2.7/logging/__init__.py", line 284, in __init__
2015-08-19 20:39:43,529 :    self.threadName = threading.current_thread().name
2015-08-19 20:39:43,529 :  File "/usr/lib/python2.7/threading.py", line 1160, in currentThread
2015-08-19 20:39:43,529 :    return _active[_get_ident()]
2015-08-19 20:39:43,529 :  File "/bin/user_wsgi_wrapper.py", line 122, in __call__
2015-08-19 20:39:43,529 :    app_iterator = self.app(environ, start_response)
2015-08-19 20:39:43,530 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
2015-08-19 20:39:43,534 :    return self.wsgi_app(environ, start_response)
2015-08-19 20:39:43,535 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
2015-08-19 20:39:43,536 :    response = self.make_response(self.handle_exception(e))
2015-08-19 20:39:43,536 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
2015-08-19 20:39:43,537 :    reraise(exc_type, exc_value, tb)
2015-08-19 20:39:43,537 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
2015-08-19 20:39:43,538 :    response = self.full_dispatch_request()
2015-08-19 20:39:43,538 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
2015-08-19 20:39:43,539 :    rv = self.handle_user_exception(e)
2015-08-19 20:39:43,539 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
2015-08-19 20:39:43,539 :    reraise(exc_type, exc_value, tb)
2015-08-19 20:39:43,540 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
2015-08-19 20:39:43,540 :    rv = self.dispatch_request()
2015-08-19 20:39:43,541 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
2015-08-19 20:39:43,541 :    return self.view_functions[rule.endpoint](**req.view_args)
2015-08-19 20:39:43,541 :  File "/home/ddircz/FIJIapp/app.py", line 103, in login
2015-08-19 20:39:43,543 :    user = models.User.get(models.User.email == form.email.data)
2015-08-19 20:39:43,543 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 4138, in get
2015-08-19 20:39:43,544 :    return sq.get()
2015-08-19 20:39:43,544 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 2740, in get
2015-08-19 20:39:43,546 :    return clone.execute().next()
2015-08-19 20:39:43,546 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 2787, in execute
2015-08-19 20:39:43,547 :    self._qr = ResultWrapper(model_class, self._execute(), query_meta)
2015-08-19 20:39:43,547 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 2470, in _execute
2015-08-19 20:39:43,548 :    return self.database.execute_sql(sql, params, self.require_commit)
2015-08-19 20:39:43,548 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 3199, in execute_sql
2015-08-19 20:39:43,549 :    self.commit()
2015-08-19 20:39:43,549 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 3048, in __exit__
2015-08-19 20:39:43,550 :    reraise(new_type, new_type(*exc_args), traceback)
2015-08-19 20:39:43,550 :  File "/home/ddircz/FIJIapp/venv/lib/python2.7/site-packages/peewee.py", line 3191, in execute_sql
2015-08-19 20:39:43,551 :    cursor.execute(sql, params or ())
2015-08-19 20:39:43,551 :peewee.OperationalError: no such table: user

Why is my database not working properly? I have searched for hours trying to find a solution, and I am quite frustrated. Any help would be much appreciated. Let me know if there is any more information I can provide. http://ddircz.pythonanywhere.com/ Thanks

You don't have user table in your database, looks like your migration is failed or something,

I definitely have a user table, as it works locally and I explicitly define it in my model. It must be some other issue.

Did you run the database setup / migrations on PythonAnywhere? Remember, it's using a different database to the one you're using locally, so you need to make sure that all of the tables are installed again.

Thanks for the response giles. I am fairly sure that I am. I define the database with:

DATABASE = SqliteDatabase('/home/ddircz/FIJIapp/social.db')

And then I initialize the Database when the app is ran using:

def initialize():
DATABASE.connect()
DATABASE.create_tables([User, Post, Relationship, Contact], safe=True)
DATABASE.close()

The database "social.db" is created in the app's directory, but it is completely empty.

Can I take a look at your code? We can see it from our side, but we always ask permission first.

Yes, you have my permission to take a look.

OK, I think I see the problem. Your initialize function is called from app.py, but only in this block:

if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            # REDACTED
        )
    except:
        pass
    app.run(debug=config.BaseConfig.DEBUG, port=5000)

This block won't be run when you're running the app under PythonAnywhere, because the app module isn't being loaded as the main one.

That's a good thing for the last line -- you definitely don't want to call app.run on PythonAnywhere, as it will lock up your web app. But the other lines in there are something that you want to run every time your app starts up.

There are three options that I can see:

  1. Move the all of the lines inside that if statement apart from the run, to outside it. This means that the database will be initialized and the user created (if it's not already there) every time that your app module is imported, but hopefully that will just be once for each worker process each time your app is started, so it should be pretty harmless
  2. Copy the code inside the if apart from the run into the WSGI file, just before you do the from app import app as application. Again, this will be run once for each worker process every time the web app reloads.
  3. Copy the code apart from the run into a separate file, and run it from a Bash console. This will (of course) mean that it's only run once, but (again, of course) you'll need to remember to re-run it any time you want the database to be re-initialized.

Thank you so much! Tried the first solution you suggested and it worked great. Much appreciated.

Great! Thanks for confirming :-)

what the fuck is the wrong with this... im not mad but i been trying the whole day to host my website please help me

"""
Created By : Ashen
Company Name : Bloppo
Company Owner : Ashen

Website Name : Bloppo(Social Media application)
Compatibility : Android, Windows, Linux, Mac ..etc.. (85% compatibility rate)
Date of Hosting: 2018 Oct 02 Tuesday

Hosted Country: Srilanka
Server: Windows Based Computer ( WSGI Server On python Flask Framework )
Framework: Flask, Jinja2

Written with : Python 3.7 (html, css, javascript)

Credits to Ashen
Copyrights Included
Terms and conditions, Privacy Policies, Disclaimers Provided on the Website

"""


import app_database as database
import posts_database as db_posts
import UserConfigs as db_UserConfig
import friends as db_friends
from flask import (Flask, render_template,
                   request, make_response,
                   url_for, redirect,
                   session, flash)

app = Flask(__name__)
app.secret_key = 'hu@#$AFASDQ#.ASDAFvcc!!@@231ASAdd'
error_array = ["Password Confirmation is wrong", "Last Name is Likely to Be inValid Make sure its bigger than 2",
               "First Name is Likely to Be inValid Make sure its bigger than 2",
               "Password Must have at least 8 characters", "Invalid Email"]
ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png']


@app.route('/')
def index():
    """Home Page or Index When First visit"""
    session['id'] = 'Guest'
    return render_template('index.html')


@app.route('/profile')
@app.route('/profile/<user_id>')
def profile(user_id=''):
    """Opens the Profile Page"""
    personpassword = database.get_password(session['id'])
    if len(user_id) > 8:
        persondata = database.profile_data(user_id)
        if persondata != 'No Record':
            return render_template('profile.html', user_info=persondata, cookies=session, password=personpassword)

    else:
        user_friend_request_list = db_UserConfig.friend_request_list(session['id'])
        user_friends = db_friends.frien_list(session['id'])
        login_response = database.get_data(session['email'], session['password'])
        return render_template('profile.html', user_info=login_response,
                               cookies=session, password=personpassword,
                               frequests=user_friend_request_list, friends=user_friends)


@app.route('/posts')
@app.route('/posts/<user_id>')
def get_posts(user_id=''):
    """Gets the Posts of a Specific User/ Current User"""
    if len(user_id) <= 8:
        user_id = session['id']

    current_posts = db_posts.get_posts(user_id)
    poster_name = database.get_name(user_id)
    password = database.get_password(user_id)

    if current_posts == 'No Posts':
        return render_template('user-posts.html', published=current_posts,
                               cookies=session, checker=user_id,
                               len_published="None",
                               writer_name=poster_name, password=password)
    else:
        return render_template('user-posts.html', published=current_posts,
                               cookies=session, checker=user_id,
                               len_published=len(current_posts.post_titles),
                               writer_name=poster_name, password=password)


@app.route('/post_post', methods=['POST'])
def create_post():
    """Creates a Post(POST)"""
    usrid = session['id']
    p_title = request.form['post_title']
    p_post = request.form['write_post']

    if len(p_title) <= 0:
        return render_template('error.html', lr='Post Creation',
                               error_type="No Title Were Entered", cookies=session)
    if len(p_post) <= 0:
        return render_template('error.html', lr='Post data Creation',
                               error_type="No Post Data Were Entered", cookies=session)
    if db_posts.create_post(usrid, p_title, p_post) == 'Created':
        flash("Post Created")
        return make_response(redirect(url_for('get_posts')))


@app.route('/delete/<identity>/<ptitle>/<pdate>/<ppost>')
def delete_post(identity, ptitle, pdate, ppost):
    """Deletes the Post That the User Requested To"""
    password = database.get_password(identity)
    if session['password'] == password:
        vanish = db_posts.delete(identity, ptitle, pdate, ppost)
        if vanish == 'instance_deleted':
            flash("Post Deleted")
            return make_response(redirect(url_for('get_posts')))
    else:
        return "You Are Not Authorised To Modify This!"


@app.route('/search', methods=['POST'])
def find_user():
    """Used in Searching for Users"""
    user_name = request.form['person_name']
    if len(user_name) >= 5:
        response = database.search_person(user_name)
        password = database.get_password(session['id'])
        if response != 'Not Found':
            return render_template('searchusers.html', usersdata=response, cookies=session, password=password)
        else:
            return render_template('searchusers.html', usersdata='None', cookies=session, password=password)


@app.route('/addfriend/<friendid>/<userid>')
def addfriend(friendid, userid):
    """Sends a Friend Request"""
    password = database.get_password(userid)
    if password == session['password']:
        sent_request = db_UserConfig.get_friend_requests(friendid, userid)
        if sent_request == 'Request Sent':
            flash('Request Sent')
            return make_response(redirect(url_for('get_posts')))
        elif sent_request == 'Requested Already':
            flash("Cant send friend request twice")
            return make_response(redirect(url_for('get_posts')))

        elif sent_request == "Already Friends":
            flash("The Person is Already Friend With You")
            return make_response(redirect(url_for('get_posts')))


@app.route('/decline/<requestor>/<user_id>')
def remove_request(requestor, user_id):
    """Removes a Friend Request That the User Got"""
    password = database.get_password(session['id'])
    if password == session['password']:
        delete = db_UserConfig.decline(requestor, user_id)
        if delete == 'Declined':
            flash("Friend Request Declined")
            return make_response(redirect(url_for('profile')))


@app.route('/accept/<requestor>')
def accept_request(requestor):
    """Accepts the Request"""
    password = database.get_password(session['id'])
    if password == session['password']:
        response = db_friends.accept_friend_request(requestor, session['id'])
        if response == 'FADDED':
            flash("Added Friend")
            return make_response(redirect(url_for('profile')))
        if response == "Failed":
            flash("Failed to Add as Friend")
            return make_response(redirect(url_for('profile')))


@app.route('/unfriend/<person>')
def unfriend(person):
    """View For Unfriending a User"""
    delete = db_friends.unfriend(person, session['id'])
    name = database.get_name(person)
    if delete == "Done":
        flash("{} was removed from the friend list".format(name))
        return make_response(redirect(url_for('profile')))
    elif delete == "Friend Not Found":
        flash("Unabe: Friend not found")
        return make_response(redirect(url_for('profile')))

    elif delete == 'Error':
        return "Unexpected Error Occured : Contact Owner Now!"


@app.route('/login', methods=['POST'])
def login():
    """Logs the User In"""
    email = request.form["email"]
    password = request.form["pass"]

    if len(email) == 0 and len(password) == 0:
        return make_response(redirect(url_for('index')))

    login_response = database.get_data(email, password)
    if login_response == 'No Record':
        return render_template('error.html', error_type='No User Found')
    elif login_response == 'De-authorised':
        return render_template('error.html', error_type='Wrong Password')
    elif login_response[0] == 'Authorised':
        session['email'] = email
        session['password'] = password
        session['id'] = login_response[4]
        flash("Login Authorised")
        return make_response(redirect(url_for('get_posts')))


@app.route('/register')
def register():
    """Opens the Registration Page"""
    return render_template('register.html')


@app.route('/registeration', methods=['POST'])
def register_user():
    """View for Registration"""
    email_r = request.form['email']
    password_r = request.form['pass']
    first_name_r = request.form['fname']
    last_name_r = request.form['lname']
    full_name_r = first_name_r + " " + last_name_r
    passconfirm = request.form['confirm_pass']

    if len(email_r) >= 8:
        if len(password_r) >= 8:
            if len(first_name_r) >= 2:
                if len(last_name_r) >= 2:
                    if password_r == passconfirm:
                        insertion_response = database.insert_data(email_r, password_r, full_name_r)
                        if insertion_response == "Saved":
                            return render_template('account_creation_verify.html', process=True)
                        elif insertion_response == "Email Exists":
                            return render_template('account_creation_verify.html', process=False)
                    else:
                        return render_template('error.html', lr='Registration', error_type=error_array[0])
                else:
                    return render_template('error.html', lr='Registration', error_type=error_array[1])
            else:
                return render_template('error.html', lr='Registration', error_type=error_array[2])
        else:
            return render_template('error.html', lr='Registration', error_type=error_array[3])
    else:
        return render_template('error.html', lr='Registration', error_type=error_array[4])


@app.route('/logout')
def logout_user():
    """Logs The User Out"""
    del session['email'], session['password'], session['id']
    flash("Logged Out")
    return make_response(redirect(url_for('index')))


# Policies and Terms
@app.route('/TermsConditions')
def terms_conditions():
    return render_template('termsCond.html')


@app.route('/PrivacyPolicies')
def privacy_policies():
    return render_template('privacyPolicy.html')


@app.route('/Disclaimer')
def disclaimer():
    return render_template('disclaimer.html')

[edit by admin: formatting]

It's pretty much impossible to debug something without knowing more details.

What error messages are you getting, if any? If you're not getting any errors, what problem are you seeing, and what would you expect to see? It would also help to have a URL on your site that shows any specific problems that you're trying to debug.