Flask HTTP請求與響應


設置請求 POST GET

設置post和get,在route中設置methods參數,除了post,get,還有put ,delete 等

  @app.route('/http_test', methods=['GET', "POST"])

1 from flask import Flask, url_for, request 2 @app.route('/http_test', methods=['GET', "POST"]) # 如果沒有methods參數,默認只支持get,必須大寫
3 def http_test(): 4     if request.method == 'POST': 5         print('post') 6         return 'post'
7     elif request.method == "GET": 8         print("GET") 9         return 'GET'

獲取請求參數

參數形式包括 from data,json,get的path參數

from flask import Flask, url_for, request
@app.route('/http_test1', methods=["GET", "POST"]) def http_test1():  # post參數{"name":"666"},application/json
    if request.method == 'POST': # request.data
        print(request.data)  # b'{"name":"666"}'
        print(type(request.data))  # <class 'bytes'>
        # request.json
        print(request.is_json)  # True
        print(request.json)  # {"name":"666"}
        print(type(request.json))  # <class 'dict'>
        return 'post'
總結就是:
request.form.get("xxx") #獲取form 數據
request.args.get("xxx") #獲取path 數據
request.json.get("xxx") #獲取json 數據
request.data #二進制數據
request.headers.get("z") #獲取header數據
request.is_json() #判斷是否是json 數據

返回響應

常見返回

1.return + "String" ,實際上是會調用make_response 2.return + render_template("path/to/temaplate",{}),返回模版 3.return + redirect #重定向,常常與url_for聯合用
  return redirect(url_for(view_func))# 重定向到某個視圖,url_for為獲取視圖路徑的函數
4.return + jsonify(**dict) 返回json數據
flask 可配置返回函數make_response
def index(): response = make_response(render_template('index.html', foo=42)) #等效於直接render_template('index.html', foo=42)
    response.headers['X-Parachutes'] = 'parachutes are cool'# 編輯response_headers 信息
    response.set_cookie('key', 'value') #設置session
    response.delete_cookie('key') return response

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM