python-web框架Flask-(三)request模塊

request模塊方法:

客戶端請求,flask中獲取客戶端的信息,需要用到request

 

首先要引入模塊:

from flask import request

1、request.method  查看請求方式

# 用戶請求http://localhost:5000/login 會執行下邊視圖函數
@app.route('/login',methods=['GET','POST']) 
def fn():
    if request.method == 'POST': # 判斷用戶請求是否是post請求
        pass
    else:
        pass

2、request.form   獲取 " POST " 相關請求提交過來的數據

@app.route('/login',methods=['GET','POST'])
def fn():
    if request.method == 'POST': # 判斷用戶請求是否是post請求
        print(request.form) # ImmutableMultiDict([('user_name', '呂星辰'), ('user_password', '123456')])
        print(request.form.get('user_name')) # 呂星辰
        print(request.form.to_dict()) # {'user_name': '呂星辰', 'user_password': '123456'}

上邊代碼,模擬了前端表單 post請求,在flask中,對於post請求,獲取數據使用form,獲取到的是一個對象,可使用get方法獲取對應的數據(如果沒有數據,get方法會返回None,但是用其他獲取單個數據方式會報錯!!!),也可以使用to_dict( )方法轉化爲字典。

3、request.args  獲取 " GET " 提交過來的請求參數 

@app.route('/login',methods=['GET','POST'])
def fn():
    print(request.args) # ImmutableMultiDict([('user_name', '呂星辰'), ('user_password', '123')])
    print(request.args.get('user_name')) # 呂星辰
    print(request.args.to_dict()) # {'user_name': '呂星辰', 'user_password': '123'}

上邊代碼,同上,模擬前端表單get請求,在flask中,對於get請求,獲取數據使用args,獲取到的是一個對象,也可使用get方法獲取對應的數據,也可以使用to_dict( )方法轉化爲字典。

 

4、request.path  獲取斜線後邊的url路徑 (不包含根路徑)

# 請求的是  http://0.0.0.0:9527/req?id=10
print(request.path) # '/req'

5、request.base_url 獲取路徑,包含根路徑

#請求 http://0.0.0.0:9527/req?id=10
print(request.base_url) # 'http://0.0.0.0:9527/req'

6、request.headers 獲取請求頭信息

'''
    Accept: text/html, application/xhtml+xml, */*
    Content-Type: application/x-www-form-urlencoded
    Accept-Language: zh-CN
    Accept-Encoding: gzip, deflate
    Host: localhost:5000
    Content-Length: 55
    Connection: Keep-Alive
    Cache-Control: no-cache
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like GeckoCore/1.70.3704.400 QQBrowser/10.4.3587.400
'''

7、request.host獲取根路徑

# 請求路徑爲 http://0.0.0.0:9527/req?id=10
print(request.host) # http://0.0.0.0:9527

8、request.host_url 獲取根路徑,包含後邊斜線

# 請求路徑爲 http://0.0.0.0:9527/req?id=10
print(request.host) # http://0.0.0.0:9527/

9、request.remote_addr 訪問的遠端ip地址

10、request.files 文件上傳

 

補充下:

ImmutableMultiDict([ ]) 是一個類字典,與字典不同的是,類字典可以儲存相同key,args和form都是類字典對象,從ImmutableMultiDict獲取數據,有兩種方法:

  (1) dict[ 'param' ]

  (2) dict.get( 'param' ) ( 推薦 )

如果key對應多個值:dict.getList( ‘param’ )  獲取的是一個列表

 

二、Request 中methods

如果視圖中含有多種請求方式,需要在路由中添加methods參數,配置請求方式,上邊事例中已經出現過:

# 用戶請求http://localhost:5000/login 會執行下邊視圖函數
@app.route('/login',methods=['GET','POST']) 
def fn():
    pass

以後會補充,先寫這麼多!!!

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