2020-04-22

Flask 接收表單資料及 query string

Flask 接收表單資料及 query string

本文的參考專案 https://github.com/shinder/flask-practice

  • request.args 可取得 GET 參數(query string)
  • request.form 可取得 POST 參數(表單資料)
  • request.files 可取得表單上傳的檔案

以下為取得 GET 和 POST 參數的例子:

@app.route('/try-qs') def queryString(): # query string 轉成 dict # http://localhost:5000/try-qs?a[]=1&b=34&a[]=5 output = { 'args': request.args, 'a[]': request.args.getlist('a[]'), 'get_b': request.args.get('b'), 'get_a[]': request.args.get('a[]'), } return output @app.route('/try-post', methods=['POST']) # 限定使用 POST def try_post(): # 表單資料 urlencoded, form-data 皆可, 使用 postman 測試 output = { 'form': request.form, 'a[]': request.form.getlist('a[]'), 'post_b': request.form.get('b'), 'post_a[]': request.form.get('a[]'), } return output @app.route('/try-post2', methods=['POST']) def try_post2(): # 使用 postman post json 資料: {"a":11,"b":22} output = { 'content_type': request.content_type, 'data': request.data.decode('utf-8'), 'json': request.get_json(), } return output

測試時,/try-post 和 /try-post2 可以使用 postman 測試。 getlist() 能取得所有相同名稱的參數,而拿到 list 類型的物件(陣列)。但不會將名稱有帶中括號的參數自動轉換為陣列。

使用 postman 將 json 文件 post 給 /try-post2 路由。request.data.decode('utf-8') 可以拿到字串;request.get_json() 可以拿到由 JSON 字串轉換而成的 dict 或 list。

沒有留言:

FB 留言