Flask-wtf

提供:Dev Guides
移動先:案内検索

フラスコ– WTF

Webアプリケーションの重要な側面の1つは、ユーザーにユーザーインターフェイスを提供することです。 HTMLは <form> タグを提供します。これは、インターフェースの設計に使用されます。 テキスト入力、ラジオ、選択などの*フォーム*要素 適切に使用できます。

ユーザーが入力したデータは、GETメソッドまたはPOSTメソッドのいずれかによって、Httpリクエストメッセージの形式でサーバー側のスクリプトに送信されます。

  • サーバー側のスクリプトは、http要求データからフォーム要素を再作成する必要があります。 したがって、実際には、フォーム要素を2回定義する必要があります(HTMLで1回、サーバー側スクリプトで1回)。
  • HTMLフォームを使用する別の欠点は、フォーム要素を動的にレンダリングすることが(不可能ではないにしても)難しいことです。 HTML自体は、ユーザーの入力を検証する方法を提供しません。

ここで、柔軟なフォーム、レンダリング、および検証ライブラリである WTForms が役立ちます。 Flask-WTF拡張機能は、この WTForms ライブラリとのシンプルなインターフェースを提供します。

*Flask-WTF* を使用して、Pythonスクリプトでフォームフィールドを定義し、HTMLテンプレートを使用してそれらをレンダリングできます。 *WTF* フィールドに検証を適用することもできます。

このHTMLの動的生成がどのように機能するかを見てみましょう。

まず、Flask-WTF拡張機能をインストールする必要があります。

pip install flask-WTF

インストール済みパッケージには Form クラスが含まれており、ユーザー定義フォームの親として使用する必要があります。

*WTforms* パッケージには、さまざまなフォームフィールドの定義が含まれています。 一部の*標準フォームフィールド*を以下に示します。
Sr.No Standard Form Fields & Description
1

TextField

<input type = 'text'> HTMLフォーム要素を表します

2

BooleanField

<input type = 'checkbox'> HTMLフォーム要素を表します

3

DecimalField

数値を小数で表示するためのテキストフィールド

4

IntegerField

整数を表示するためのTextField

5

RadioField

<input type = 'radio'> HTMLフォーム要素を表します

6

SelectField

選択フォーム要素を表します

7

TextAreaField

<testarea> htmlフォーム要素を表します

8

PasswordField

<input type = 'password'> HTMLフォーム要素を表します

9

SubmitField

<input type = 'submit'>フォーム要素を表します

たとえば、テキストフィールドを含むフォームは次のように設計することができます-

from flask_wtf import Form
from wtforms import TextField

class ContactForm(Form):
   name = TextField("Name Of Student")
*'name'* フィールドに加えて、CSRFトークンの非表示フィールドが自動的に作成されます。 これは、 *Cross Site Request Forgery* 攻撃を防ぐためです。

レンダリングされると、これは以下に示すように同等のHTMLスクリプトになります。

<input id = "csrf_token" name = "csrf_token" type = "hidden"/>
<label for = "name">Name Of Student</label><br>
<input id = "name" name = "name" type = "text" value = ""/>

ユーザー定義フォームクラスはFlaskアプリケーションで使用され、フォームはテンプレートを使用してレンダリングされます。

from flask import Flask, render_template
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'development key'

@app.route('/contact')
def contact():
   form = ContactForm()
   return render_template('contactl', form = form)

if __name__ == '__main__':
   app.run(debug = True)

WTFormsパッケージには、バリデータクラスも含まれています。 フォームフィールドに検証を適用するのに役立ちます。 次のリストは、一般的に使用されるバリデーターを示しています。

Sr.No Validators Class & Description
1

DataRequired

入力フィールドが空かどうかを確認します

2

Email

フィールド内のテキストが電子メールIDの規則に従っているかどうかを確認します

3

IPAddress

入力フィールドのIPアドレスを検証します

4

Length

入力フィールドの文字列の長さが指定された範囲内にあるかどうかを検証します

5

NumberRange

指定された範囲内の入力フィールドの数値を検証します

6

URL

入力フィールドに入力されたURLを検証します

連絡先フォームの name フィールドに 'DataRequired' 検証ルールを適用します。

name = TextField("Name Of Student",[validators.Required("Please enter your name.")])

フォームオブジェクトの* validate()*関数はフォームデータを検証し、検証が失敗した場合に検証エラーをスローします。 *エラー*メッセージがテンプレートに送信されます。 HTMLテンプレートでは、エラーメッセージは動的にレンダリングされます。

{% for message in form.name.errors %}
   {{ message }}
{% endfor %}

次の例は、上記の概念を示しています。 Contact form のデザインは、*(forms.py)*の下にあります。

from flask_wtf import Form
from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField,
   SelectField

from wtforms import validators, ValidationError

class ContactForm(Form):
   name = TextField("Name Of Student",[validators.Required("Please enter
      your name.")])
   Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])
   Address = TextAreaField("Address")

   email = TextField("Email",[validators.Required("Please enter your email address."),
      validators.Email("Please enter your email address.")])

   Age = IntegerField("age")
   language = SelectField('Languages', choices = [('cpp', 'C&plus;&plus;'),
      ('py', 'Python')])
   submit = SubmitField("Send")

バリデーターは Name および Email フィールドに適用されます。

以下は、Flaskアプリケーションスクリプト*(formexample.py)*です。

from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'development key'

@app.route('/contact', methods = ['GET', 'POST'])
def contact():
   form = ContactForm()

   if request.method == 'POST':
      if form.validate() == False:
         flash('All fields are required.')
         return render_template('contactl', form = form)
      else:
         return render_template('successl')
      elif request.method == 'GET':
         return render_template('contactl', form = form)

if __name__ == '__main__':
   app.run(debug = True)

テンプレート*(contactl)*のスクリプトは次のとおりです-

<!doctype html>
<html>
   <body>
      <h2 style = "text-align: center;">Contact Form</h2>

      {% for message in form.name.errors %}
         <div>{{ message }}</div>
      {% endfor %}

      {% for message in form.email.errors %}
         <div>{{ message }}</div>
      {% endfor %}

      <form action = "http://localhost:5000/contact" method = post>
         <fieldset>
            <legend>Contact Form</legend>
            {{ form.hidden_tag() }}

            <div style = font-size:20px; font-weight:bold; margin-left:150px;>
               {{ form.name.label }}<br>
               {{ form.name }}
               <br>

               {{ form.Gender.label }} {{ form.Gender }}
               {{ form.Address.label }}<br>
               {{ form.Address }}
               <br>

               {{ form.email.label }}<br>
               {{ form.email }}
               <br>

               {{ form.Age.label }}<br>
               {{ form.Age }}
               <br>

               {{ form.language.label }}<br>
               {{ form.language }}
               <br>
               {{ form.submit }}
            </div>

         </fieldset>
      </form>
   </body>
</html>

Pythonシェルで formexample.py を実行し、URL http://localhost:5000/contact にアクセスします。 以下に示すように、 Contact フォームが表示されます。

フォームの例

エラーがある場合、ページは次のようになります-

フォームエラーページ

エラーがない場合は、「成功」*がレンダリングされます。

フォーム成功ページ