In my projects __init__.py I have this:
app = Flask(__name__)
app.config.from_object('config')
CsrfProtect(app)
db = SQLAlchemy(app)
My development config file looks like:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
WTF_CSRF_ENABLED = True
SECRET_KEY = 'supersecretkey'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'project.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
And in my unittest setUp I have this:
from project import app, db
class ExampleTest(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
self.app = app.test_client()
db.create_all()
In theory, setting WTF_CSRF_ENABLED to False here should prevent CSRF for the unit tests, however I'm still getting CSRF errors if I do a POST while unit testing. I think it is because I have already called CsrfProtect(app) while WTF_CSRF_ENABLED is True (when I import app, it is called). If I set WTF_CSRF_ENABLED = False in the config file, it works as expected.
Is there anyway I can disable CSRF after it has already been enabled? Or am I barking up the wrong tree here?
You can disable CSRF protection in all views by default, by setting WTF_CSRF_CHECK_DEFAULT to False , and selectively call protect() only when you need. This also enables you to do some pre-processing on the requests before checking for the CSRF token.
The FlaskForm base class is defined by the Flask-WTF extension, so it is imported from flask_wtf . The fields and validators, however, are imported directly from the WTForms package. The list of standard HTML fields supported by WTForms is shown in Table 4-1. Table 4-1. WTForms standard HTML fields.
You can disable it using the config variable WTF_CSRF_ENABLED
,
for example
class TestConfig(Config):
TESTING = True
WTF_CSRF_ENABLED = False
...
or app.config['WTF_CSRF_ENABLED'] = False
See also flask-WTF documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With