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 Broadcasting Add Some Layout

Jovan Dandridge
Jovan Dandridge
12,835 Points

Hi, i keep getting that the database is locked how do i fix this?

Need help on unlocking the database

8 Answers

The solution for the locked database issue is in the teacher's notes of the Macros video: https://teamtreehouse.com/library/build-a-social-network-with-flask/takin-names/macros

Use this code in models.py:

@classmethod
    def create_user(cls, username, email, password, admin=False):
        try:
            with DATABASE.transaction():
                cls.create(
                    username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
        except IntegrityError:
            raise ValueError("User already exists")
Jovan Dandridge
Jovan Dandridge
12,835 Points

delete this: DATABASE = SqliteDatabase('social.db') from model.py?

delete social.db from you workspace directory, when you run your app.py file a new database will be created. Personally i did this project locally as i got fed up with this lock issue.

Hi Jovan

I have had this issue alot in workspaces too, try deleting the database and run the script again.

V K
V K
5,237 Points

I tried deleting DATABASE = SqliteDatabase('social.db')

in my models.py file

When I tried to run the app.py file I got this message

"AttributeError: module "models' has no attribute 'initialize'

Hi Vk

Can you post your code for the app.py file. Models don't have a attribute called initialize.

Jovan Dandridge
Jovan Dandridge
12,835 Points

Thanks Andreas! its working now

V K
V K
5,237 Points

Here is my code for app.py

from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import (LoginManager, login_user, logout_user,
                             login_required)

import forms
import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secret_key = 'auoesh.bouoastuh.43,uoausoehuosth3ououea.auoub!'

login_manager = LoginManager()
login_manager.init_app(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 the database connection after each request."""
    g.db.close()
    return response


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


@app.route('/login', methods=('GET', 'POST'))
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Your email or password doesn't match!", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You've been logged in!", "success")
                return redirect(url_for('index'))
            else:
                flash("Your email or password doesn't match!", "error")
    return render_template('login.html', form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash("You've been logged out! Come back soon!", "success")
    return redirect(url_for('index'))


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



if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username='kennethlove',
            email='kenneth@teamtreehouse.com',
            password='password',
            admin=True
        )
    except ValueError:
        pass
    app.run(debug=DEBUG, host=HOST, port=PORT)

Andreas cormack

does your models.py have a function called initialize() ??

def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User], safe=True)
    DATABASE.create_tables([Post], safe=True)
    DATABASE.close()
V K
V K
5,237 Points

Andreas cormack

No, I will add that code now.

Edit: I had it..but apparently it was deleted when i was copying it from pycharm.

I added it..but it didn't work

V K
V K
5,237 Points

Andreas cormack

Here is my code for models.py

import datetime

from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
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',)

    def get_posts(self):
        return Post.select().where(Post.user == self)

    def get_stream(self):
        return Post.select().where(
            (Post.user == self)
        )

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


class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='posts'
    )
    content = TextField()

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

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

now when I run app.py I get a NameError: name 'DATABASE' is not defined.

that's strange. I cannot see anything wrong. I replaced my app.py and models.py code with yours and i dont get any errors!!.

V K
V K
5,237 Points

Andreas cormack

I just copy n pasted everything I just posted..and I got it to work. I really don't understand what happened. I appreciate you taking the time to try to help me. Thanks again!

no worries, that's what i am here for.