在fastapi的实际应用中发现,fastapi没有提供像flask中的g这样的上下文相关的东西。所以在查找了多方的资料发现,可以使用中间件,再加上Python3.7中的新特性contextvar可以实现应用上下文的管理。
contextvar可自行到官网进行学习。
这里着重讲解一下fastapi中怎么应用。
fastapi中的中间件,可实现对每次请求的request对象进行操作,然后执行请求内容,最后也可以对返回response进行处理。middleware用法参考我之前的文章。
fastapi基于starlette,所以starlette中的中间键可直接用于fastapi。
我在starlette的中间件中找到,starlette_context这个开源项目,可以直接拿来使用,但是它内置的请求只处理了几个头部信息,并不能完全符合项目要求。于是对其进行改造。这里具体讲解一下这个开源项目的原理过程,方便进行与自身需求符合的改进。
starlette_context
starlette_context目录结构:
starlette_context
plugins
__init__.py
plugin.py
.
.
.
__init__.py
ctx.py
header_keys.py
middleware.py
其中__init__.py
直接引入了contextvar,并对其进行初始化
from contextvars import ContextVar
_request_scope_context_storage: ContextVar[str] = ContextVar(
"starlette_context"
)
from starlette_context.ctx import context # noqa: E402, F401
其中ctx.py,主要对contextvar对象进行管理,并实现了一个data函数属性,以获得全部值。
from collections import UserDict
from typing import Any
from contextvars import copy_context
from libs.fd_context import _request_scope_context_storage
class _Context(UserDict):
"""
A mapping with dict-like interface.
It is using request context as a data store.
Can be used only if context has been created in the middleware.
If you know Flask, it can be compared to g object.
"""
def __init__(self, *args: Any, **kwargs: Any):
# not calling super on purpose
if args or kwargs:
raise AttributeError("Can't instantiate with attributes")
@property
def data(self) -> dict:
"""
Dump this to json. Object itself it not serializable.
"""
try:
return _request_scope_context_storage.get()
except LookupError as e:
raise RuntimeError(
"You didn't use ContextMiddleware or "
"you're trying to access `context` object "
"outside of the request-response cycle."
) from e
def exists(self) -> bool:
return _request_scope_context_storage in copy_context()
def copy(self) -> dict:
"""
Read only context data.
"""
import copy
return copy.copy(self.data)
context = _Context()
data属性主要通过contextvar实例的get方法获取数据。
header_keys.py,定义需要获取的信息字段。
class HeaderKeys:
correlation_id = "X-Correlation-ID"
request_id = "X-Request-ID"
date = "Date"
forwarded_for = "X-Forwarded-For"
user_agent = "User-Agent"
middleware.py主要是继承自BaseHTTPMiddleware。初始化时传入plugins列表。实现set_context方法,功能是遍历plugins,根据request请求获取值并返回header_keys中定义的键对应的值。dispatch方法是中间件必须实现的方法,并必须调用call_next
from contextvars import Token
from typing import Optional, Sequence
from starlette.middleware.base import (
BaseHTTPMiddleware,
RequestResponseEndpoint,
)
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import Response
from libs.fd_context import _request_scope_context_storage
from libs.fd_context.plugins import Plugin
from libs.fd_context import plugins
class ContextMiddleware(BaseHTTPMiddleware):
"""
Middleware that creates empty context for request it's used on.
If not used, you won't be able to use context object.
"""
def __init__(
self, plugins: Optional[Sequence[Plugin]] = None, *args, **kwargs
) -> None:
super().__init__(*args, **kwargs)
self.plugins = plugins or ()
if not all([isinstance(plugin, Plugin) for plugin in self.plugins]):
raise TypeError("This is not a valid instance of a plugin")
async def set_context(self, request: Request) -> dict:
"""
You might want to override this method.
The dict it returns will be saved in the scope of a context.
You can always do that later.
"""
return {
plugin.key: await plugin.process_request(request)
for plugin in self.plugins
}
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
_starlette_context_token: Token = _request_scope_context_storage.set(
await self.set_context(request)
)
try:
response = await call_next(request)
for plugin in self.plugins:
await plugin.enrich_response(response)
finally:
_request_scope_context_storage.reset(_starlette_context_token)
return response
plugins中主要的文件就是plugin.py。
Plugin类是一个元类,其中
定义了key变量用于存放header_key中的值,value变量用于存放获取到的值。
可实现方法从request中获取到头部信息,以及starlette中对requests中的所有解析信息都可以自己实现相应的方法。