- Notifications
You must be signed in to change notification settings - Fork10
pyx/sanic-wtf
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Sanic-WTF makes usingWTForms withSanic and CSRF (Cross-Site RequestForgery) protection a little bit easier.
pip install --upgrade Sanic-WTF
fromsanicimportSanicapp=Sanic(__name__)# either WTF_CSRF_SECRET_KEY or SECRET_KEY should be setapp.config['WTF_CSRF_SECRET_KEY']='top secret!'@app.middleware('request')asyncdefadd_session_to_request(request):# setup session
fromsanic_wtfimportSanicFormfromwtforms.fieldsimportPasswordField,StringField,SubmitFieldfromwtforms.validatorsimportDataRequiredclassLoginForm(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 currentrequest object when you instantiate the form class. Sanic-WTF will do thetrick.
fromsanicimportresponse@app.route('/',methods=['GET','POST'])asyncdefindex(request):form=LoginForm(request)ifrequest.method=='POST'andform.validate():name=form.name.datapassword=form.password.data# check user password, log in user, etc.returnresponse.redirect('/profile')# here, render_template is a function that render template with contextreturnresponse.html(awaitrender_template('index.html',form=form))
Note
For WTForms users: please note that SanicForm requires the whole requestobject instead of some sort of MultiDict.
For more details, please see documentation.
BSD New, see LICENSE for details.