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

Doesn't work locally

Trying to run the code at this point and get this error:

127.0.0.1 - - [26/Nov/2018 16:43:19] "GET / HTTP/1.1" 500 - Traceback (most recent call last): File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 2309, in call return self.wsgi_app(environ, start_response) File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 1811, in full_dispatch_request rv = self.preprocess_request() File "/Users/davidbronfen/.local/share/virtualenvs/flask-basics-413pK2kd/lib/python3.6/site-packages/flask/app.py", line 2087, in preprocess_request rv = func() File "/Users/davidbronfen/Projects/flask-basics/login-demo/app.py", line 31, in before_request g.db = models.database.db.connect() AttributeError: module 'models' has no attribute 'database'

models.py

import datetime

from flask_bcrypt import generate_password_hash
from flask_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',)

    @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")


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

app.py

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

import models
import forms

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'


app = Flask(__name__)
app.secret_key = 'ncunwcqpcq-e9fhobefvql9wc;03FA;DOFVBAEV'

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.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.RegistrationForm()
    if form.validate_on_submit():
        flash("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('/')
def index():
    return 'Hey'


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

4 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,722 Points

This is a namespace issue-- database is part of the Model class and DATABASE is the global peewee database.

@app.before_request
def before_request():
    """Connect to the database before each request."""
    g.db = models.database.db.connect()

should be

@app.before_request
def before_request():
    """Connect to the database before each request."""
    g.db = models.DATABASE.connect()
Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Tech Web,

The clue is in this part of the Traceback:

File "/Users/davidbronfen/Projects/flask-basics/login-demo/app.py", line 31, in 
before_request g.db = models.database.db.connect() 
AttributeError: module 'models' has no attribute 'database'

It's telling you that in your app.py you are calling: models.database.db.connect(), and that models has no attribute called database.

Let's look over at your models.py, and sure enough you have no attribute there called database. You do have one called DATABASE. Try replacing models.database.db.connect() with models.DATABASE.db.connect().

Cheers

Alex

Jeff Muday
Jeff Muday
Treehouse Moderator 28,722 Points

Alex, you're working on the same schedule as me! Beat me to another answer!!

J llama
J llama
12,631 Points

yeah it doesn't work locally cuz kenneth doesn't explain anything.. i love how the errors were quickly covered up and not at all explained in this one L O L

Thank you, Jeff and Alex! Now I do not know who to choose as the best answer :)