Flask - 請求和響應
阿新 • • 發佈:2021-02-03
目錄
請求
- 獲取請求相關的需要匯入
request
request.method
: 獲取請求方法request.args
: 獲取GET請求引數request.form
: 獲取POST請求引數request.values
: 內容是form和args, 可以使用values替代form和argsrequest.cookies
: 獲取請求cookiesrequest.headers
: 獲取請求頭request.files
: 上傳檔案obj = request.files['the_file_name']
: 根據檔名獲取物件.obj.save('/var/www/uploads/' + secure_filename(f.filename))
secure_filename
: 生成檔名request.path
: 獲取斜線後邊的url路徑 (不包含根路徑request.url
: 獲取全部urlrequest.base_url
: 獲取域名和請求檔案路徑request.url_root
: 獲取域名request.host_url
: 獲取根路徑,包含後邊斜線request.host
: 獲取根路徑
響應
-
返回字串 :
return "index"
-
返回模板並新增引數 :
return render_template('index.html', n1=123)
-
重定向 :
return redirect('/index')
-
響應Response物件 : 使用
make_response()
函式接受字串和錯誤碼.response = make_response(render_template('index.html'))
- 設定請求頭 :
response.headers['X-something'] = 'A value'
- 設定cookies :
response.set_cookies('key', 'value')
- 刪除cookies :
response.delete_cookie('key')
- 設定請求頭 :
-
生成一個response並返回
- 第一種方法
from flask import Response, json
Response( json.dumps({'a': 1, 'b':1}),content_type='application/json')
- 第二種方法
from flask import jsonify
jsonify({'a': 1, 'b': 2})