其他分享
首页 > 其他分享> > DI of FASTAPI

DI of FASTAPI

作者:互联网

DI (Dependency Injection)

https://www.freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/

依赖注入

当一个类A依赖另外一个类B时候, 此类A不需要自己创建被依赖类B,

而是有外部创建,一般是框架创建, 然后注入到类A中。

When class A uses some functionality of class B, then its said that class A has a dependency of class B.

In Java, before we can use methods of other classes, we first need to create the object of that class (i.e. class A needs to create an instance of class B).

So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.

1*TF-VdAgPfcD497kAW77UkgWhat if code could speak?

 

三种注入方式

There are basically three types of dependency injection:

  1. constructor injection: the dependencies are provided through a class constructor.
  2. setter injection: the client exposes a setter method that the injector uses to inject the dependency.
  3. interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

控制反转,依赖注入的背后概念

依赖类 和 被依赖类 不应该直接关联,

他们应该都依赖于抽象接口,

接口就相当于契约

符合契约的 这两种类, 拥有依赖关系, 保证了 两者的替换的灵活性,即扩展性。

Inversion of control —the concept behind DI

This states that a class should not configure its dependencies statically but should be configured by some other class from outside.

It is the fifth principle of S.O.L.I.D — thefive basic principles of object-oriented programming and design by Uncle Bob — which states that a class should depend on abstraction and not upon concretions (in simple terms, hard-coded).

According to the principles, a class should concentrate on fulfilling its responsibilities and not on creating objects that it requires to fulfill those responsibilities. And that’s where dependency injection comes into play: it provides the class with the required objects.

Note: If you want to learn about SOLID principles by Uncle Bob then you can head to this link.

 

好处:

有利于单元测试

提高扩展性

低耦合

Benefits of using DI

  1. Helps in Unit testing.
  2. Boiler plate code is reduced, as initializing of dependencies is done by the injector component.
  3. Extending the application becomes easier.
  4. Helps to enable loose coupling, which is important in application programming.

 

缺点:

有些复杂

编译时候错误被推移到运行时态

IDE中不好查找调用关系

Disadvantages of DI

  1. It’s a bit complex to learn, and if overused can lead to management issues and other problems.
  2. Many compile time errors are pushed to run-time.
  3. Dependency injection frameworks are implemented with reflection or dynamic programming. This can hinder use of IDE automation, such as “find references”, “show call hierarchy” and safe refactoring.

 

Django 依赖非显式声明

https://www.runoob.com/django/django-cookie-session.html

例如如下请求响应函数,入参为request,但是此函数对依赖资源的限制,需要编码实现。

例如只有登录成功才能访问,这样的要求,需要响应函数中自己实现,

但是往往很多响应函数都有此要求。

造成重复编码,依赖不清晰,不便于维护。

def index(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login') # 收到浏览器的再次请求,判断浏览器携带的cookie是不是登录成功的时候响应的 cookie
    if not status:
        return redirect('/login/')
    return render(request, "index.html")


def logout(request):
    rep = redirect('/login/')
    rep.delete_cookie("is_login")
    return rep # 点击注销后执行,删除cookie,不再保存用户状态,并弹到登录页面
   
def order(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login')
    if not status:
        return redirect('/login/')
    return render(request, "order.html")

 

FASTAPI对各种资源的依赖声明方法

COOKIE

https://fastapi.tiangolo.com/tutorial/cookie-params/

from typing import Union

from fastapi import Cookie, FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
    return {"ads_id": ads_id}

 

Query

https://fastapi.tiangolo.com/tutorial/query-params-str-validations/

from typing import Union

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results

 

Path

https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

 

Body

https://fastapi.tiangolo.com/tutorial/body-fields/

from typing import Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

 

header

https://fastapi.tiangolo.com/tutorial/header-params/

from typing import Union

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: Union[str, None] = Header(default=None)):
    return {"User-Agent": user_agent}

 

可编程依赖

https://fastapi.tiangolo.com/tutorial/dependencies/

from typing import Union

from fastapi import Depends, FastAPI

app = FastAPI()


async def common_parameters(
    q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
    return {"q": q, "skip": skip, "limit": limit}


@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons


@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
    return commons

 

标签:return,DI,FASTAPI,app,id,item,fastapi,class
来源: https://www.cnblogs.com/lightsong/p/16656340.html