Describes how to generate a SECRET_KEY In the Python Flask framework.
Introduction
If you encounter an error message "Must provide secret_key to use csrf", the cause is that secret_key is not set. Add
app.config[‘SECRET_KEY‘]=‘xxx‘
SECRET_KEY should not be written in the code.
It is best to set a config. py file to read the content from it.
Config. py
CSRF_ENABLED = TrueSECRET_KEY = ‘you-will-never-guess‘
App. py
app.config.from_object(‘config‘)
This prevents csrf.
Well, let's talk about this SECRET_KEY:
A Simple Method for Flask to generate SECRET_KEY (key)
SECRET_KEY is an important configuration value in Flask. This article introduces a simple method for generating SECRET_KEY.
Session, Cookies, and some third-party extensions all use the SECRET_KEY value. This is a very important configuration value and should be set to a value that is hard to guess. The random value is better.
The random problem is that it is difficult to determine what is true random. A key should be random enough. Your operating system can generate beautiful random values based on a random password generator. This value can be used as a key:
>>> import os>>> os.urandom(24)'\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'
Copy and paste the value to your code, and you will get the key.
Setting method:
app = Flask(__name__)app.config['SECRET_KEY'] = '\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'# orapp.secret_key = '\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'# orapp.config.update(SECRET_KEY='\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\')