☆☆ 新着記事 ☆☆

2020年7月6日月曜日

FLASK request methodと応用(テキストクリックで値を送信)


Contents
◇FLASK_WTFを使わないで、htmlからアプリにデータを渡すrequest methodを使った基本的な書き方。( CSRF 攻撃対策などを簡易に実現するToolはない。)

◇サブミット・ボタンを使わないで、テキストをクリックすることで値を送信する方法/




◇ request methodを使った基本的な書き方。
request libraryをflaskからインポートする。
(Flask_WTFを使う場合はインポートは必須ではない。)

・html
<body>
    {% if message %}
    <p>{{ message }}</p>
    {% endif %}

    <form action="" method="post">
        <p>
            <label for="username">Username</label>
            <input type="text" name="username">
        </p>
        <p>
            <label for="password">Password</label>
            <input type="password" name="password">
        </p>
        <p>
            <input type="submit">
        </p>
    </form>
</body>




・app.py

from flask import Flask, render_template, request

#...

@app.route('/login/', methods=['post', 'get'])

def login():

    message = ''

    if request.method == 'POST':
        username = request.form.get('username')  # access the data inside
        password = request.form.get('password')

        if username == 'root' and password == 'pass':
            message = "Correct username and password"
        else:
            message = "Wrong username or password"

    return render_template('login.html', message=message)






◇サブミット・ボタンを使わないで、テキストをクリックすることで値を送信する方法
ちょっとミスリーディングなタイトル。本当はSubmitボタンを使うが、SubmitボタンのフレームをCSSで見えないように書き換える。

 ・CSS

.sample input[type="submit"]{
border:none;
background:#FFF;
text-decoration:underline;color:#00f; }

.sample input:hover { cursor:pointer; }


・html

<br />
<form action="/リンク先" class="sample" method="post" name="form1">
<input name="name" type="hidden" value="Apple" />
<input type="submit" value="Apple" />
</form>