try:returnnext(iterator)exceptStopIteration:raise_StopIterationasyncdefiterate_in_threadpool(iterator:Iterator)->AsyncGenerator:whileTrue:try:yieldawaitrun_in_threadpool(_next,iterator)except_StopIteration:break
handler(request, exc) else: response = await run_in_threadpool(self.handler, request, exc) # 判断是否为协程, 不是则以线程池方式运行 await response(scope, receive, send) # 我们总是不断地抛出异常。 # 这允许服务器记录错误, # 或者允许测试客户端在测试用例中选择性地提出错误。 raise exc from...
from starlette.concurrency import run_in_threadpoolP = ParamSpec("P")class BackgroundTask: def __init__( self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs ) -> None: self.func = func self.args = args...
from starlette.concurrency import run_in_threadpoolP = ParamSpec("P")class BackgroundTask: def __init__( self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs ) -> None: self.func = func self.args = args ...
response = await run_in_threadpool(handler, request, exc) # 通过回调函数生成的response处理请求 await response(scope, receive, sender) 2.2.用户中间件 接着就是用户中间件了, 这个也是我们接触最多的中间件, 在使用starlette.middleware时, 我们都会继承于一个叫BaseHTTPMiddleware的中间件, 然后基于如下代码...
(request)else:response=awaitrun_in_threadpool(handler,request)awaitresponse(self.scope,self.receive,self.send)asyncdefmethod_not_allowed(self,request:Request)->Response:# 如果我们在starlette应用中运行, 且抛出了一个错误# 那么可配置的异常处理程序, 便可处理返回的response并触发一场# 对于简单的ASGI程序...
="/":# 如果类型为http 且 自身存在重定向符 且 路径不为根路径redirect_scope=dict(scope)ifscope["path"].endswith("/"):redirect_scope["path"]=redirect_scope["path"].rstrip("/")else:redirect_scope["path"]=redirect_scope["path"]+"/"# 路径如果包含/则去掉, 不包含则加上forrouteinself....
from starlette.concurrency import run_in_threadpoolclass BackgroundTask: def __init__( self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any ) -> None: self.func = func self.args = args self.kwargs = kwargs self.is_async = asyncio.iscoroutinefunction(func)...
import asyncio import typing from starlette.concurrency import run_in_threadpool class BackgroundTask: def __init__( self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any ) -> None: self.func = func self.args = args self.kwargs = kwargs self.is_async = asyncio.iscor...
# this has to be an async endpoint because Starlette calls run_in_threadpool # on sync endpoints which has it's own set of peculiarities w.r.t propagating # contextvars (it propagates them forwards but not backwards) async def homepage(request): assert ctxvar.get() == "set ...