Search code examples
pythonpyramidwtforms

How can I use CSRF protection with WTForms and Pyramid?


How can I use CSRF protection with WTForms and Pyramid?

In flask, there's a WTForms module which handles this.

What would be a way to have this with Pyramid as well without creating spaghetti code implemented in main logic and with all forms?


Solution

  • CSRF protection in WTForms is handled by subclasses of class SecureForm. You should implement a subclass of SecureForm that uses Pyramid's facilities to store tokens in user session and to obtain tokens as they come with a request for verification.

    A good implementation to follow is the one for Flask, in flask.ext.wtf.Form class. This is a small class that should port to Pyramid without much effort.