Skip to main content

Sanic-WTF - Sanic meets WTForms

Project description

Sanic-WTF makes using WTForms with Sanic and CSRF (Cross-Site Request Forgery) protection a little bit easier.

Quick Start


pip install --upgrade Sanic-WTF

How to use it

Intialization (of Sanic)

from sanic import Sanic

app = Sanic(__name__)

# either WTF_CSRF_SECRET_KEY or SECRET_KEY should be set
app.config['WTF_CSRF_SECRET_KEY'] = 'top secret!'

async def add_session_to_request(request):
    # setup session

Defining Forms

from sanic_wtf import SanicForm
from wtforms import PasswordField, StringField, SubmitField
from wtforms.validators import DataRequired

class LoginForm(SanicForm):
    name = StringField('Name', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Sign In')

That’s it, just subclass SanicForm and later on passing in the current request object when you instantiate the form class. Sanic-WTF will do the trick.

Form Validation

from sanic import response

@app.route('/', methods=['GET', 'POST'])
async def index(request):
    form = LoginForm(request)
    if request.method == 'POST' and form.validate():
        name =
        password =
        # check user password, log in user, etc.
        return response.redirect('/profile')
    # here, render_template is a function that render template with context
    return response.html(await render_template('index.html', form=form))


For WTForms users: please note that SanicForm requires the whole request object instead of some sort of MultiDict.

For more details, please see documentation.


BSD New, see LICENSE for details.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for Sanic-WTF, version 0.5.0
Filename, size File type Python version Upload date Hashes
Filename, size Sanic_WTF-0.5.0-py2.py3-none-any.whl (6.5 kB) File type Wheel Python version py2.py3 Upload date Hashes View hashes
Filename, size Sanic-WTF-0.5.0.tar.gz (11.9 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page