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 To the ends of the request

Problem with after_request decorator (Flask)

I am on Task 3 of 3.

I can't find the error here... Someone please help!

Thanks in advance, Alexander :dizzy:

app.py
from flask import Flask, g

import models

app = Flask(__name__)


@app.before_request
def before_request():
    g.db = models.DATABASE

@app.after_request
def after_request(response):
    g.db.close()
    return response

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

You're doing great! But the reason that you can't close the connection to the database is because you never created the connection to the database :smiley: Take a look

from flask import Flask, g

import models

app = Flask(__name__)


@app.before_request
def before_request():
    g.db = models.DATABASE
    g.db.connect()  #note the connection to the database here

@app.after_request
def after_request(response):
    g.db.close()
    return response

Hope this helps! :dizzy:

Thank you! That worked! I forgot the .connect() part XD I totally don't know what I was thinking about

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Alexander Davison I don't for a second think it was all your fault. Technically, it shouldn't have passed the second step in my opinion. Look at this quote from step 2:

"Now add a function named before_request that sets g.db to the DATABASE variable in models and calls the .connect() method. "

It should have failed when it did not detect a connection to the database. So you just skipped merrily on your way to step 3 and then tried to close something that was never open. Woops! But it happens to everyone :smiley: