一文帶你學會Python?Flask框架設置響應頭
導讀
本篇博客我們將全面了解 Flask 中關于請求的相關設置,開始前你需要先配置 Flask 的基礎框架。
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def index():
response = make_response("Hello, 夢想橡皮擦")
response.headers['Content-Type'] = 'text/html; charset=utf-8'
return response
if __name__ == '__main__':
app.run()
運行代碼,得到下述效果。

Python Flask 設置響應頭
response.headers 屬性
response.headers 是 Flask 框架中的一個屬性,它是一個字典類型,用于存儲響應頭信息。這個屬性可以在視圖函數(shù)中直接使用,用于設置響應頭的信息。
比如在視圖函數(shù)中,可以使用下面的代碼來設置 Content-Type 響應頭:
response.headers['Content-Type'] = 'text/plain'
如果你想要設置其它響應頭,可以使用同樣的方式,例如:
response.headers['X-My-Header'] = 'Xiang_Pi_Ca'
通過開發(fā)者工具,可以查看到自定義的響應頭內(nèi)容。

注意,在設置響應頭之前,你需要創(chuàng)建一個響應對象。可以使用 flask.make_response() 函數(shù)來創(chuàng)建一個響應對象,例如:
from flask import make_response
response = make_response("Hello, Xiang_Pi_Ca!")
response.headers['Content-Type'] = 'text/plain'
flask.abort() 函數(shù)返回特定狀態(tài)碼
使用 flask.abort() 函數(shù)來返回特定狀態(tài)碼的響應,并設置響應頭。例如,在請求中包含無效參數(shù)時返回 400 Bad Request:
from flask import Flask, abort
app = Flask(__name__)
@app.route('/')
def index():
# 模擬參數(shù)錯誤
invalid_parameter = True
if invalid_parameter:
abort(400)
return "Hello, Xiang_Pi_Ca!"
if __name__ == '__main__':
app.run()
代碼運行效果:

Flask 中可設置的響應頭參數(shù)
在 Flask 中,你可以設置任何 HTTP 協(xié)議定義的響應頭參數(shù)。
常用的響應頭包括:
- Content-Type:用于指定響應體的 MIME 類型。例如,'Content-Type': 'text/html' 表示響應體是 HTML 文檔。
- Content-Length: 用于指定響應體的長度。
- Location:用于重定向。例如,'Location': 'https://pachong.vip' 會導致瀏覽器重定向到 https://pachong.vip。
- Cache-Control: 用于控制緩存,例如,'Cache-Control': 'no-cache' 表示瀏覽器不應緩存響應。
- Expires: 用于指定緩存過期時間。
- Etag:用于指定資源的 ETag 值。
- Server: 用于指定服務器的名稱和版本。
- Access-Control-Allow-Origin: 用于控制跨域資源共享。
其他關于響應頭的配置
除了在視圖函數(shù)中設置響應頭之外,F(xiàn)lask 還提供了其他方式來配置響應頭。
使用中間件
中間件可以在請求和響應之間添加額外的處理。你可以使用中間件來設置響應頭。
中間件是一種在請求和響應之間添加額外處理的機制,可以使用中間件來設置響應頭。
下面的代碼實現(xiàn)了一個中間件,在每個請求之前設置 Content-Type 和 X-My-Ca 響應頭。
from flask import Flask, request,make_response
app = Flask(__name__)
@app.before_request
def before_request():
response = make_response()
response.headers['Content-Type'] = 'application/json'
response.headers['X-My-Ca'] = 'xiangpica_demo'
return response
@app.route('/')
def index():
return "Hello, 夢想橡皮擦!"
使用裝飾器
裝飾器是一種在不改變視圖函數(shù)本身的情況下添加額外處理的方法。
下面的代碼實現(xiàn)了一個裝飾器,在每個視圖函數(shù)執(zhí)行之前設置 Content-Type 和 X-My-Ca 響應頭。
from flask import Flask, request, make_response
from functools import wraps
app = Flask(__name__)
def set_headers(f):
@wraps(f)
def decorated_function(*args, **kwargs):
response = make_response(f(*args, **kwargs))
response.headers['Content-Type'] = 'application/json'
response.headers['X-My-Header'] = 'xiangpica_demo_'
return response
return decorated_function
@app.route('/')
@set_headers
def index():
return "Hello, 夢想橡皮擦!"
if __name__ == '__main__':
app.run()
上述代碼可以實現(xiàn)每當路由被調(diào)用時,裝飾器都會在視圖函數(shù)之前設置 Content-Type 和 X-My-Ca 響應頭。
使用配置
應用程序配置是一種在不修改應用程序代碼的情況下更改應用程序行為的方法。
from flask import Flask, make_response
app = Flask(__name__)
app.config.update(
RESPONSE_HEADERS={
'Content-Type': 'application/json',
'X-My-Ca': 'xiangpica_demo_'
}
)
@app.route('/')
def index():
response = make_response()
for key, value in app.config['RESPONSE_HEADERS'].items():
response.headers[key] = value
return response
if __name__ == '__main__':
app.run()
上述代碼在配置中定義了 'Content-Type' 和 'X-My-Ca' 兩個響應頭,在路由函數(shù)中就可以使用 make_response() 函數(shù)來創(chuàng)建響應對象,然后遍歷配置中的響應頭來添加響應頭了,該寫法的優(yōu)點是,我們可以在不修改應用程序代碼的情況下更改響應頭, 也可以根據(jù)環(huán)境來設置不同的響應頭。
使用第三方擴展
Flask 有許多第三方擴展可以幫助你更簡單的配置響應頭, 比如 Flask-Cors,F(xiàn)lask-Security 等,這些內(nèi)容以后用單獨的博客進行說明。
到此這篇關于一文帶你學會Python Flask框架設置響應頭的文章就介紹到這了,更多相關Python Flask框架內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pytorch實現(xiàn)用CNN和LSTM對文本進行分類方式
今天小編就為大家分享一篇pytorch實現(xiàn)用CNN和LSTM對文本進行分類方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
利用Python如何批量修改數(shù)據(jù)庫執(zhí)行Sql文件
這篇文章主要給大家介紹了關于利用Python如何批量修改數(shù)據(jù)庫執(zhí)行Sql文件的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-07-07
解決Tensorboard可視化錯誤:不顯示數(shù)據(jù) No scalar data was found
今天小編就為大家分享一篇解決Tensorboard可視化錯誤:不顯示數(shù)據(jù) No scalar data was found,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

