How do you solve the error KeyError: 'A secret key is required to use CSRF.' when using a wtform in

I have been trying to build a web app using flask and wtforms and a firebase database, but I keep getting the error message "KeyError: 'A secret key is required to use CSRF.'" and I don't know how to solve it. here is my code:

I have been trying to build a web app using flask and wtforms and a firebase database, but I keep getting the error message "KeyError: 'A secret key is required to use CSRF.'" and I don't know how to solve it. here is my code:

from flask import Flask, render_template, request from firebase import firebase from flask_wtf import FlaskForm from flask_wtf.csrf import CSRFProtect, CSRFError from wtforms import DateField, StringField, TextAreaField from wtforms.validators import DataRequired from wtforms_components import TimeField app = Flask(__name__) csrf = CSRFProtect(app) firebase = firebase.FirebaseApplication("https://uhungry-f9563.firebaseio.com", None) class myForm(FlaskForm): event = StringField("event", validators=[DataRequired()]) location = StringField("location", validators=[DataRequired()]) startDay = DateField("startDay", validators=[DataRequired()]) startTime = TimeField("startTime", validators=[DataRequired()]) endDay = DateField("endDay", validators=[DataRequired()]) endTime = TimeField("endTime", validators=[DataRequired()]) details = TextAreaField("details", validators=[DataRequired()]) count = 0 @app.route('/', methods=['GET' , 'POST']) def home(): form = myForm() if form.validate_on_submit(): global count count += 1 putData = {'Event': form.event.data, 'Location': form.location.data, 'startDay': form.startDay.data, 'startTime': form.startTime.data,'endDay': form.endDay.data, 'endTime': form.endTime.data, 'Details': form.details.data} firebase.put('/events', 'event' + str(count), putData) return render_template("trial.html") return render_template("home.html") if __name__ == '__main__': app.run(debug=True) 
1

5 Answers

You are getting this error because you haven't set up a secret key. Without a secret key you can't use many features such as flash, flask-login and of course, as you have experienced, CSRF protection.

The easiest way to solve this would be to set up a secret key in your app config file but unlike what the other answers have shown, it is strongly recommended to save all of your Keys (especially keys to some paid APIs or services such as AWS) in a separate .env file that is not shared when the code is distributed. Luckily, for the secret key, you don't have to worry about the environment variables and you can just create a random secret key as follows:

import os SECRET_KEY = os.urandom(32) app.config['SECRET_KEY'] = SECRET_KEY 
2

you need to add a SECRET_KEY in the application configuration to take advantage of csrf protection and provide a WRF CSRF SECRET_KEY otherwise your secret key will be used instead

app.config.update(dict( SECRET_KEY="powerful secretkey", WTF_CSRF_SECRET_KEY="a csrf secret key" )) 
3

Add this line to your app code:

app.config['SECRET_KEY'] = 'any secret string' 
1

I fixed the problem by adding SECRET_KEY = 'mysecret' in the config.py

file and then made sure to add the config when I call create_app() like that

env = os.environ.get('FLASK_ENV', 'dev') app = create_app('app.config.%sConfig' % env.capitalize()) 

You need to add the secret key like this:

from flask import Flask, session app = Flask(__name__) app.secret_key = secret_key # Set the secret key for the Flask application @app.route('/') def index(): # Your view logic here pass 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa3BuaGyAcYOOoaawZZSkerq71GaqqKSmmnq1tMRmnKuqn6d6rLHYnqmrp6Jirm6%2FxJypnqxdoLK6ecisZKudoaq2s7HDZquoZaWosm6v0qudZq%2BYmg%3D%3D

ncG1vNJzZmifk6uyb63MrGpnnJmctrWty6ianpmeqL2ir8SsZZynnWS1sMOMnaZmsZ%2BqerS7y6%2BcZqyYmnqmvtGoqWajla6ys77Oq2SaZaOasLOx02ainrFdnsBuvsSqrKKqlZl6tbuMrqqeZZOov6d51qGcp2WlqLavs4yaZLCslqS%2FrnnIp2WhrJ2h

 Share!