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

后端 未结 3 470
借酒劲吻你
借酒劲吻你 2021-02-05 02:59

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.\'

相关标签:
3条回答
  • 2021-02-05 03:34

    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
    
    0 讨论(0)
  • 2021-02-05 03:54

    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"
    ))
    
    0 讨论(0)
  • 2021-02-05 03:58

    Add this line to your app code:

    app.config['SECRET_KEY'] = 'any secret string'
    
    0 讨论(0)
提交回复
热议问题