Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask Takin' Names Macros

Andrew Bruce
Andrew Bruce
7,822 Points

Peewee database OperationalError

I get this error when I run the app, when I debug it seems to point to an issue with DATABASE.connect() in my models.py, but the code is the same as the project files so I can't see what is wrong. Can anyone help? Project files below -

FlaskSocialNetwork.py

from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask_login import LoginManager

import forms
import models

app = Flask(__name__)
app.secret_key = "drtgrfedwfoklmrefkp[slwmergkpfdwqklerd"

login_manager = LoginManager(app)

login_manager.login_view = 'login'


@login_manager.user_loader
def load_user(userid):
    try:
        return models.User.get(models.User.id == userid)
    except models.DoesNotExist:
        return None

@app.before_request
def before_request():
    """Connect to the database before each request"""

    g.db = models.DATABASE
    g.db.connect()

@app.after_request
def after_request(response):
    """Close database connection after each request"""
    g.db.close()
    return response


@app.route('/register', methods=('GET', 'POST'))
def register():
    form = forms.RegistrationForm()
    if form.validate_on_submit():
        flash("Registration complete", "success")
        models.User.create_user(
            username=form.username.data,
            email = form.password.data,
            password = form.password.data
        )
        return redirect(url_for('index'))
    return render_template('registration.html', form=form)


@app.route('/')
def index():
    return 'Index Page'


if __name__ == '__main__':
    models.initialize()

    try:
        models.User.create_user(
            username='abruce',
            email='abruce1711@gmail.com',
            password='password',
            admin=True
        )
    except ValueError:
        pass
    app.run(debug=True, host="0.0.0.0")

models.py

import datetime

from flask_login import UserMixin
from flask_bcrypt import generate_password_hash, check_password_hash
from peewee import *


DATABASE = SqliteDatabase('social.db')


class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = DATABASE
        order_by = ('-joined_at',)

    @classmethod
    def create_user(cls, username, email, password, admin=False):
        try:
            cls.create(
                username=username,
                email=email,
                password=generate_password_hash(password),
                is_admin=admin
            )
        except IntegrityError:
            raise ValueError("User already exists")


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

I couldn't seem to format the full error test so I pasted a screenshot here - https://snag.gy/IHlbY6.jpg

Thank you in advance!

Andrew Bruce
Andrew Bruce
7,822 Points

Note - I tried running the models.py file by itself, calling the initialize() method from there then creating a test user. This works fine. So it must be something to do with the FlaskSocialNetwork.py file, although I can't figure out where the problem is.

2 Answers

Andrew Bruce
Andrew Bruce
7,822 Points

The database was in the same folder. After hours of troubleshooting I copied all of the code into a new app.py and it ran fine, maybe the file was corrupt.

Jeffrey James
Jeffrey James
2,636 Points

Is your database file on the same level as the models.py file which is trying to connect to it? Meaning, the sqlite database could be in another folder.