前提
現在、Flaskを利用してウェブアプリケーションを作成しています。
そこにSQLを用いた検索機能を実装したいのですが、
現在のコードでは検索ワードを何も入力していない項目がある場合、検索結果にテーブル内の全レコードが表示されるなど正常に検索されません。
何か良い方法はありますでしょうか。
処理の流れとしては、
- HTMLからPOST送信
- Flaskで受け取り
- localhost内のMariaDBにselect文で検索
- render_templateでselect文の実行結果を送信
という流れにしたいです。
また、検索ワードは
- text1は部分一致検索
- text2~3は完全一致検索
- ラジオボタンは必ずどちらか選択されている
となっています。
実現したいこと
- 検索ワードが入力されていない項目を条件から外す(もしくは無視する)
ソースコード
検索画面
HTML
1<!-- search.html --> 2 3<form action="{{ url_for('search') }}" method="post"> 4 text1: 5 <input type="text" name="text1"> 6 text2: 7 <input type="text" name="text2"> 8 text3: 9 <input type="text" name="text3"> 10 radio: 11 <input type="radio" value="radio1"> 12 <input type="radio" value="radio2" > 13 <input type="submit" value="検索"> 14</form>
検索結果
HTML
1<!-- result.html --> 2 3{% for res in result %} 4 <tr> 5 <td class="col-2"> 6 {{ res.text1' }} 7 </td> 8 <td class="col-2"> 9 {{ res.text2 }} 10 </td> 11 <td class="col-2"> 12 {{ res.text3 }} 13 </td> 14 <td class="col-2"> 15 {{ res.radio }} 16 </td> 17 </tr> 18{% endfor %}
Flask
Python
1# app.py 2 3@app.route("/search", methods=["POST"]) 4def search(): 5 text1 = '%' + request.form.get("text1") + '%' 6 text2 = request.form.get("text2") 7 text3 = request.form.get("text3") 8 radio = request.form.get("radio") 9 dbmg = db_manager.db_manager() 10 11 sql ="select * from db where text1 like %s or text2=%s or text3=%s or radio=%s" 12 result = dbmg.exec_query(sql,(text1,text2,text3,radio)) 13 return render_template("result.html", result=result)
DB処理
Python
1# db_manager.py 2 3import pymysql 4import pymysql.cursors 5 6class db_manager(): 7 def connect(self): 8 return pymysql.connect( 9 host="localhost", # DBサーバのアドレス 10 user=***, # DBのユーザ名 11 passwd=***, 12 db="app", # 接続するDB名 13 charset="utf8", # 文字コード 14 cursorclass=pymysql.cursors.DictCursor # 検索結果のデータ型(辞書型) 15 ) 16 17 def exec_query(self,sql,params=()): 18 with self.connect() as conn : 19 with conn.cursor() as cursor: 20 cursor.execute(sql,params) 21 results = cursor.fetchall() 22 conn.commit() 23 24 return results
試したこと
if文で検索ワードの有無を判定して条件分岐させる(現実的ではないと思い中止)
補足情報(ツールのバージョン)
Python3(Flask・PyMySQL)
MariaDB
Ubuntu
Apache