FastAPI 學習之路(十三)Cookie 參數,Header參數


系列文章:

  FastAPI 學習之路(一)fastapi--高性能web開發框架

  FastAPI 學習之路(二)

  FastAPI 學習之路(三)

  FastAPI 學習之路(四)

  FastAPI 學習之路(五)

      FastAPI 學習之路(六)查詢參數,字符串的校驗

  FastAPI 學習之路(七)字符串的校驗

    FastAPI 學習之路(八)路徑參數和數值的校驗

  FastAPI 學習之路(九)請求體有多個參數如何處理?

  FastAPI 學習之路(十)請求體的字段

      FastAPI 學習之路(十一)請求體 - 嵌套模型 

    FastAPI 學習之路(十二)接口幾個額外信息和額外數據類型

   我們先來看下如何獲取Header參數。代碼實現

from typing import Optional

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")

def read_items(user_agent: Optional[str] = Header(None)):

    return {"User-Agent": user_agent}

我們看下接口請求

 

 

 

這樣我們在請求的時候就可以獲取接口的請求參數了,我們可以在這里做一些特殊的處理。后續在項目的中增加。

        我們看下如何實現帶cookie參數。

from typing import Optional
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
def read_items(ads_id: Optional[str] = Cookie(None)):
    print(ads_id)
    return {"ads_id": ads_id}

       其實也是很簡單的,我們這里請求下看下。

 

 

 

我們簡單的做了一個請求。

        這樣我們在后續的請求中,我們可以對於header或者cookie做特殊的處理。

        我們寫一個簡單的demo。我們要求header的必須有token且token必須是456,沒有返回無權限,cookie必須有一個name,且等於123,否則返回認證失敗。

        我們看下如何實現呢

from typing import Optional
from fastapi import Cookie, FastAPI,Header
app = FastAPI()
@app.get("/items/")
def read_items(name:  Optional[str] = Cookie(None),
               token: Optional[str] =  Header(None)):
    if token is None or token!='456':
        return '無權限'
    if name is None or name !="123":
        return  "認證失敗"

 我們看下接口請求

 

 我們看下不帶token

 

   token不等於456

 

 

 我們看下cookie 中的name不等於123,token正確

 

 

        接口可以正常返回。

文章首發在公眾號,歡迎關注。


免責聲明!

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



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