Flask-request筆記

一、如何使用Postman

學會使用Postman軟件,作爲後臺測試數據使用,代碼是不是出錯,在Postman中send後看IDEA中是否報錯。

  • POST->輸入url->body->form-data->輸入Key、value->send。在Body中顯示結果。
  • 注意:get請求參數在request.args裏面,在post中輸入是要在路徑url中傳入鍵值。
  • post請求參數在request.form裏面
    以POST請求:
@app.route("/min", methods=['Post'])
def index_post():
    args = request.form
    return "Post" + str(min(int(args['x']), int(args['y'])))

以GET請求:

@app.route("/min", methods=['Get'])
def index_get():
    args = request.args
    return "Get" + str(min(int(args['x']), int(args['y'])))

在這裏插入圖片描述

二、請求方式:POST、GET

1、關於request:

  • 客戶端發送參數,雲端計算返回結果給客戶端
  • 訪問方式爲 http://IP:PORT/Router。eg 127.0.0.1:5000/index?city=shenzhen&country=china
  • request包含所有請求信息:請求頭、請求體、請求參數。
  • request 中包含了前端發送過來的所有請求數據
  • 導入 from flask import request
  • 請求頭參數中user-agent用來表示用戶用的是什麼瀏覽器。
  • 被訪問的是服務端,去訪問的是客戶端

2、關於Get請求

  • Get請求傳遞多個參數:地址?參數名=參數值&…參數可以多傳,但是需要的必須存在。
  • Get請求如何傳遞單個參數:地址?參數名=參數值

3、關於POST請求

  • post請求數據存在請求體中

4、如何在瀏覽器中查看request

  • 瀏覽器訪問url,按F12,看Query String Parameters中參數輸入。
    在這裏插入圖片描述
  • Network中Headers-> Request Method爲Get
  • Status code 爲200,含義見下表。
    在這裏插入圖片描述
    在這裏插入圖片描述在這裏插入圖片描述

三、request中的form、agrs的使用方法

from flask import Flask, request

app = Flask(__name__)

# 127.0.0.1:5000/index?city=shenzhen&country=china ?後的爲查詢字符串


@app.route("/index", methods=['GET', "POST"])
def index(): 
    # 通過request.form可以直接提取請求體中的表單格式的數據,是一個類字典對象
    # 通過get只能拿到同名參數的第一個
    name = request.form.get("name")
    age = request.form.get("age")
    city = request.args.get("city")
    name_list = request.form.getlist("name") # 獲取相同鍵名的值的方法
    # args獲取url路徑(查詢字符串)中的數據,form、data是提取請求體裏面的數據,所以postman中輸入city key值不會打印出值爲NONE
    # http://127.0.0.1:5000/index?city=shenzhen 在路徑中輸入
    # print("request.data: %s" % request.data)
    # return "name = %s, age = %s, city = %s" % (name, age, city)
    return f"name = {name}, age = {age}, city = {city}, name = {name_list}"
    # 注意前邊加f


if __name__ == '__main__':
    app.run(debug=True)

在這裏插入圖片描述

四、兩種方式訪問

if request.method == "GET":
    pass
elif request.method == "POST":
    pass

五、上傳文件

Flask中可以直接用這句上傳文件

 file_obj.save("./demo1.png")
from flask import Flask, request

app = Flask(__name__)

@app.route("/upload", methods=["POST"])
def upload():
    """
    接收前端傳過來的文件
    :return:
    """
    file_obj = request.files.get("pic")
    if file_obj is None:
        # 表示沒有發送文件
        return "未上傳文件"
    # 第一種方法
    # 將文件保存到本地
    # 1、創建一個文件
    f = open("./demo.jpg", "wb")
    # 2、向文件寫內容
    data = file_obj.read()
    f.write(data)
    # 3.關閉文件
    f.close()
    return "上傳成功"
 
    # 第二種方法:
    # # 直接使用上傳的文件對象保存
    # file_obj.save("./demo1.png")
    # return "上傳成功"


if __name__ == '__main__':
    app.run(debug=True)

在這裏插入圖片描述在這裏插入圖片描述

六、上下文管理器with()

# coding:utf-8

with open("./1.txt", "wb") as f:
    f.write("hello flask")

在這裏插入圖片描述

# coding:utf-8

class Foo(object):
    def __enter__(self):
        """
        進入with語句的時候被with調用
        :return:
        """
        print("enter called")

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        離開with語句的時候被with調用
        :param exc_type:
        :param exc_val:
        :param exc_tb:
        :return:
        """
        print("exit called")
        print("exc_type:%s" % exc_type)
        print("exc_val:%s" % exc_val)
        print("exc_tb:%s" % exc_tb)


with Foo() as foo:
    print("hello python")
    a = 1/0
    print("hello end")

with自動調用Flask中的__enter__函數,關閉的時候自動調用__exit__函數。
eg:with調用Foo類中的__enter__函數打印enter called,打印print語句hello python ,執行a = 1/0語句,發生異常,調用__exit__函數,打印exit called,處理異常。
在這裏插入圖片描述在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章