Show community: Starlette-WTF (Simple tool for integrating Starlette and WTForms)

Hi Everyone,

I created a simple tool for integrating Starlette with WTForms. It’s modeled on Flask-WTF and it’s designed to make it easier to validate forms and add CSRF protection to your apps. Here’s the quickstart from the documentation ( Check it out and let me know what you think!

from jinja2 import Template
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import PlainTextResponse, HTMLResponse
from starlette_wtf import StarletteForm, CSRFProtectMiddleware, csrf_protect
from wtforms import StringField
from wtforms.validators	import DataRequired

class MyForm(StarletteForm):
    name = StringField('name', validators=[DataRequired()])

template = Template('''
    <form method="post" novalidate>
      {{ form.csrf_token }}
        {{'Name') }}
        {% if -%}
        <span>{{[0] }}</span>
        {%- endif %}
      <button type="submit">Submit</button>

app = Starlette(middleware=[
    Middleware(SessionMiddleware, secret_key='***REPLACEME1***'),
    Middleware(CSRFProtectMiddleware, csrf_secret='***REPLACEME2***')

@app.route('/', methods=['GET', 'POST'])
async def index(request):
    """GET|POST /: form handler
    form = await MyForm.from_formdata(request)
    if form.validate_on_submit():
        return PlainTextResponse('SUCCESS')

    html = template.render(form=form)
    return HTMLResponse(html)
1 Like