☆☆ 新着記事 ☆☆

2018年11月4日日曜日

Flask/Jinja2 GET/POST Methodと応用(テキストクリックで値を送信)

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

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




request libraryをflaskからインポートする。(Flask_WTFを使う場合はインポートは必須ではない。)
Flask/Jinjaでhtmlのフォームから入力された値を取得するのは、デフォルトで 'Get Method'だけど、Flask/Jinjaのビュー内で、メソッドを指定してあげることが可能。

(Directory構成)
---test.py
 |
 |---templates
         |--- sample01.html
         |--- sample02.html



例)
test.py
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
    message="Hi, Charlie!"
    return render_template("sample01.html", message=message)
   
@app.route('/add',methods=['POST'])
def add():
    if request.method =='POST':
        result = request.form['new_wish'] # Formのname elementで指定する。
    #else:
    #    result = "No wish! Ah?"
       
    return render_template("sample02.html", result=result)
if __name__ == '__main__':
    app.run(debug=True)


sample01.html

<html>
 <head>
   <meta charset="utf-8">
 </head>
 <body>
{{message}}
<form action="/add" method="post"> 
<p>Input new make you wish to add to the list:</p>
<input type="text" name="new_wish" >
<input type="submit" value="Do">
</form>
</body>
</html>

sample02.html
<html>
 <head>
   <meta charset="utf-8">
 </head>
 <body>

<p>Now we know the brand of the car you want is</p>
{{result}}
</body>
</html>



*)Form のnameに '_' (アンダーバー:origina_area 等)を使うと上手く 'POSTで pyファイル側に
 渡せずにエラーになることがある。 (不安定) _ を無くすと、そのままでも動いたことがある。

参考)
簡易validateの方法
@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)


request.form["something"] vs request.form.get("something"),
https://www.reddit.com/r/cs50/comments/5saebt/pset_7_flask_requestform_vs_requestformget/?sort=new

Both methods are all about dictionary access. For us, our dictionaries are the underlying database table. ".get()" is a non-flask-specific method for use with dictionaries whereby you ask for a specific value and, if it does not exist, provide an alternate return value, so as to prevent an error from being thrown.
Example: if your dictionary is dict = {'name' : 'David'}, then x = dict.get('Age', None) will return x = None, since your dictionary contains only one { key : value } pair, and 'Age' is not a key in your dictionary. In general, the syntax is dictionary.get('key', value to return if 'key' is not found).
Example aside, if you look at the login method in the distribution code for PSET 7, request.form.get() does not specify an alternate value to return if the variable you request is not available. This is a point of confusion (for me), as it seems to ignore the virtue of using .get().
request.form["random_key"] attempts to access your dictionary directly without contemplating the possibility that the desired key does not exist. If the key is not found, an aptly named KeyError is thrown, which can be handled using Python error-handling code (e.g., a try block).
Still, a question remains: Why would you choose one over the other?

◇サブミット・ボタンを使わないで、テキストをクリックすることで値を送信する方法
ちょっとミスリーディングなタイトル。本当は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>


参考)

https://www.youtube.com/watch?v=IIi6e5oDZ68

0 件のコメント:

コメントを投稿