2017-12-18 10 views
0

は、私は非常に単純なコードを持っている - Imはよりよい解決策私の場合を探して: 私が持っている: - 2入力テキスト+ボタンPython/FLASK - html形式の文字列を返します。番号が含まれているかどうかチェックするには?

入力フォームを提出するには、常に文字列としてテキストを返します。 は、リスト内のすべての文字を収集し、入力からのテキストがのリストにない場合は、を収集する以外は、数値(および数値以外の場合 - 「エラー」を表示する)を解決します。

from flask import Flask, render_template, request 

app = Flask(__name__) 

@app.route("/licz/", methods=['GET']) 
def search(): 
    licz1 = request.args.get('liczba1') 
    licz2 = request.args.get('liczba2') 
    notnumbers = ['q','w','e','r','t','y'] 
    if licz1 and licz2 != None: 

     if licz1 not in notnumbers: 
      sumaliczenia = int(licz1) + int(licz2) 
      return render_template('liczenie.html', suma=sumaliczenia) 
     else: 
      sumaliczenia = "error" 
      return render_template('liczenie.html', suma=sumaliczenia) 

    else: 
     return render_template('liczenie.html') 

app.run(debug=True) 

テンプレートコード(以下のコメントから):あなたはintに、あなたの入力をキャストしようとすることができ

<!DOCTYPE html> 
    <html lang="en"> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Formularz</title> 
    </head> 
    <body> Result is {{ suma }} 
     <form action="/licz/" method="get"> 
     <input type="text" name="liczba1"> 
     <input type="text" name="liczba2"> <button type="submit">Send</button> 
     </form> 
    </body> 
    </html> 
+0

いいえ、入力テキストは常に文字列ではなくintを返すため、重複しません。 – Kris

+0

私の知る限り、あなたはさまざまな選択肢があります:(1)https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/のような 'type =" number "を使ったHTML経由(2)データをPython内部でtry/exceptを使ってintに変換する、(3)正規表現を使って文字列の中でintを検出する、(4)stringのリスト表現を比較するすべての数字のリスト '0 ... 9' – albert

+0

テンプレートコードを提供してください。 – albert

答えて

0

。数値がない場合、PythonはValueErrorを発生させます。この値は、エラーの内容を捕まえて実行することができます。

try: 
    input1 = int(input1) 
    input2 = int(input2) 
except ValueError as e: 
    # print error 
else: 
    # valid 
    sum = input1 + input2 
関連する問題