zoukankan      html  css  js  c++  java
  • FastAPI依赖注入系统系列(四) 路径操作装饰器中的依赖项

    一、路径操作装饰器中添加依赖项

    在某些场景中你可能不需要在路径操作函数中去接收依赖项的返回值,或者这个依赖项根本没有返回值。但是你仍然需要去执行这些依赖项。

    对于这些场景,不要通过在路径操作函数中去声明Depends参数,你可以在路径操作装饰器中去添加一个dependencies的列表。

    比如:

    from fastapi import Depends, FastAPI, Header, HTTPException
    
    app = FastAPI()
    
    
    async def verify_token(x_token: str = Header(...)):
        if x_token != "fake-super-secret-token":
            raise HTTPException(status_code=400, detail="X-Token header invalid")
    
    
    async def verify_key(x_key: str = Header(...)):
        if x_key != "fake-super-secret-key":
            raise HTTPException(status_code=400, detail="X-Key header invalid")
        return x_key
    
    
    @app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
    async def read_items():
        items = [
            {"name": "apple", "price": "1.12"},
            {"name": "pear", "price": "3.14"}
        ]
        return items

    上面的verify_token、verify_key依赖项和正常的依赖项一样的执行,但是它们的的返回值(如果它们存在return返回值)不会传递给路径操作函数。

    二、依赖项注意事项

    虽然上述的依赖项时放在dependencies的列表中,但是它们可以像正常依赖项一样:

    • 声明请求的参数、请求头(Header)等
    async def verify_key(x_key: str = Header(...)):
        if x_key != "fake-super-secret-key":
            raise HTTPException(status_code=400, detail="X-Key header invalid")
        return x_key
    • 这些依赖项与正常依赖项一样可以抛出异常,这些异常是会在前台返回的
    async def verify_key(x_key: str = Header(...)):
        if x_key != "fake-super-secret-key":
            raise HTTPException(status_code=400, detail="X-Key header invalid")
        return x_key
    • 尽管依赖有返回值,但是不会被使用
    async def verify_key(x_key: str = Header(...)):
        if x_key != "fake-super-secret-key":
            raise HTTPException(status_code=400, detail="X-Key header invalid")
        return x_key
    作者:iveBoy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    GridView小知识1
    ASP 中 GridView 的粗浅入门
    SQL连接
    Microsoft Visual Studio 2010 Express for Windows Phone 新建文件 设置启动
    转载一个应届计算机毕业生2012求职之路
    百度之星平衡负载(3.23)
    查找字符串中首个非重复字符
    CreateMutex函数
    关于“Visual Studio 遇到了异常,可能是由于某个扩展导致的”的解决
    无法打开预编译头文件:“Debug\****.pch”: No such file or directory 的解决办法
  • 原文地址:https://www.cnblogs.com/shenjianping/p/14862797.html
Copyright © 2011-2022 走看看