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

Exception: Must provide secret key to use csrf

When I attempt to access the .../register view I am getting the following error in the browser;

builtins.Exception Exception: Must provide secret_key to use csrf.

Traceback (most recent call last)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/treehouse/workspace/app.py", line 42, in register
form = forms.RegisterForm()
File "/usr/local/lib/python3.6/site-packages/wtforms/form.py", line 212, in __call__
return type.__call__(cls, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_wtf/form.py", line 96, in __init__
*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/wtforms/ext/csrf/form.py", line 22, in __init__
self.csrf_token.current_token = self.generate_csrf_token(csrf_context)
File "/usr/local/lib/python3.6/site-packages/flask_wtf/form.py", line 101, in generate_csrf_token
return generate_csrf(self.SECRET_KEY, self.TIME_LIMIT)
File "/usr/local/lib/python3.6/site-packages/flask_wtf/csrf.py", line 43, in generate_csrf
raise Exception('Must provide secret_key to use csrf.')
Exception: Must provide secret_key to use csrf.

The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error. To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame dump(obj) dumps all that's known about the object

I have an app.secret_key variable in app.py, do I need to include it anywhere in the register view? Nothing was mentioned about this in the video.

[MOD: added ```python formatting -cf]

4 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

You misspelled secret_key in the code posted above.

Fix that and you will be have a working piece of code.

:facepalm:

Must have looked at it a hundred times and just didn't see it. Thank you for having better eyes than me.

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Seeing your code would help debug the issue. For starters, try reviewing the examples on CSRF in the flask documentation and this dev.to article.

Post back if you need more help. Good luck!!!

Code is here.

Thanks for those links, I'll try review the examples, but CSRF has only been alluded to in the course, it hasn't been taught yet, so I don't even know what it is.

from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask.ext.login import LoginManager

import forms
import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secrer_key = 'ginqchty7y&&BTBnhfn32ny7y&T&^N^Buhniubt723b7i'

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):
    """Clost 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('/')
def index():
    return 'Hey'



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

Followed the dev.to guide in workspacesand got the following error;

treehouse:~/workspace$ python app.py
Traceback (most recent call last):
File "app.py", line 3, in <module>
from flask_wtf.csrf import CSRFProtect
ImportError: cannot import name 'CSRFProtect'
treehouse:~/workspace$

Jeff Muday
Jeff Muday
Treehouse Moderator 28,720 Points

A cool "Saturday project" is rolling your own CSRF protection. It's not conceptually difficult, but there are a few things to think through. More importantly, it will give you an appreciation for what WTforms, Flask-wtf, and Flask-login bring to projects.