https://github.com/pyx/sanic-wtf
Sanic meets WTForms
https://github.com/pyx/sanic-wtf
csrf-protection sanic wtforms
Last synced: 10 months ago
JSON representation
Sanic meets WTForms
- Host: GitHub
- URL: https://github.com/pyx/sanic-wtf
- Owner: pyx
- License: other
- Created: 2017-04-27T22:39:13.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2023-10-06T02:13:09.000Z (over 2 years ago)
- Last Synced: 2025-04-05T19:03:02.686Z (11 months ago)
- Topics: csrf-protection, sanic, wtforms
- Language: Python
- Size: 74.2 KB
- Stars: 26
- Watchers: 6
- Forks: 10
- Open Issues: 5
-
Metadata Files:
- Readme: README.rst
- License: LICENSE
Awesome Lists containing this project
README
===============================
Sanic-WTF - Sanic meets WTForms
===============================
Sanic-WTF makes using `WTForms`_ with `Sanic`_ and CSRF (Cross-Site Request
Forgery) protection a little bit easier.
.. _WTForms: https://wtforms.readthedocs.io/en/3.0.x/
.. _Sanic: https://github.com/channelcat/sanic
Quick Start
===========
Installation
------------
.. code-block:: sh
pip install --upgrade Sanic-WTF
How to use it
-------------
Intialization (of Sanic)
^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: python
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!'
@app.middleware('request')
async def add_session_to_request(request):
# setup session
Defining Forms
^^^^^^^^^^^^^^
.. code-block:: python
from sanic_wtf import SanicForm
from wtforms.fields 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
^^^^^^^^^^^^^^^
.. code-block:: python
from sanic import response
@app.route('/', methods=['GET', 'POST'])
async def index(request):
form = LoginForm(request)
if request.method == 'POST' and form.validate():
name = form.name.data
password = form.password.data
# 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))
.. note::
For WTForms users: please note that `SanicForm` requires the whole `request`
object instead of some sort of `MultiDict`.
For more details, please see documentation.
License
=======
BSD New, see LICENSE for details.
Links
=====
- `Documentation `_
- `Issue Tracker `_
- `Source Package @ PyPI `_
- `Git Repository @ Github
`_
- `Git Repository @ Gitlab
`_
- `Development Version
`_