FastAPI中的Flask拆卸请求等效功能

huangapple go评论62阅读模式
英文:

Flask teardown request equivalent in Fastapi

问题

在FastAPI中,你可以使用app.middleware("http")(your_middleware_function)来实现与Flask中teardown_request类似的功能。下面是一个示例:

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def close_session_middleware(request: Request, call_next):
    response = await call_next(request)
    storage.close_session()
    return response

# 其他路由和处理程序

上面的代码中,close_session_middleware函数会在每次HTTP请求处理完成后自动执行,并在其中关闭数据库会话。

希望这对你有帮助!如果你需要更多信息,请随时提出。

英文:

I am building a rest api with fastapi. I implemented the data layer separately from the fastapi application meaning I do not have direct access to the database session in my fastapi application.

I have access to the storage object which have method like close_session which allow me to close the current session.

Is there a equivalent of flask teardown_request in fastapi?

Flask Implementation

from models import storage
.....
.....

@app.teardown_request
def close_session(exception=None):
    storage.close_session()

I have looked at fastapi on_event('shutdown') and on_event('startup'). These two only runs when the application is shutting down or starting up.

答案1

得分: 2

我们可以通过使用依赖项来实现这一点。

感谢williamjemir点击这里阅读github讨论

from fastapi import FastAPI, Depends                           
from models import storage
                                                                                                                   
async def close_session() -> None:  
  """Close current after every request."""
  print('Closing current session')
  yield                         
  storage.close()  
  print('db session closed.')

app = FastAPI(dependencies=[Depends(close_session)])                        
                                                                                                                                          

@app.get('/')
def home():
   return "Hello World"                                             

if __name__ == '__main__':
  import uvicorn  
  uvicorn.run(app)
英文:

We can do this by using dependency.

credit to williamjemir: Click here to read the github discussion

from fastapi import FastAPI, Depends                           
from models import storage
                                                                                                                   
async def close_session() -> None:  
  """Close current after every request."""
  print('Closing current session')
  yield                         
  storage.close()  
  print('db session closed.')

app = FastAPI(dependencies=[Depends(close_session)])                        
                                                                                                                                          
@app.get('/')                                                        
def home():                                                          
   return "Hello World"                                             
                                                                    
if __name__ == '__main__':                                           
  import uvicorn  
  uvicorn.run(app)

答案2

得分: 1

# 使用 FastAPI 中间件

> 一个 "中间件" 是在任何特定路径操作处理请求之前与每个请求一起工作的函数并且在返回每个响应之前也起作用

 - 它接收到您应用的每个请求
 - 然后可以对该请求执行某些操作或运行任何必要的代码
 - 然后将请求传递给应用程序的其余部分通过某个路径操作进行处理
 - 然后获取应用程序生成的响应通过某个路径操作)。
 - 它可以对该响应执行某些操作或运行任何必要的代码
 - 然后返回响应

示例

```python
import time

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    # 在处理请求之前执行某些操作
    response = await call_next(request)
    # 在响应生成后执行某些操作
    return response

参考链接:


<details>
<summary>英文:</summary>

# use fastapi middleware

&gt; A &quot;middleware&quot; is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it.

 - It takes each request that comes to your application.
 - It can then do something to that request or run any needed code.
 - Then it passes the request to be processed by the rest of the application (by some path operation).
 - It then takes the response generated by the application (by some path operation).
 - It can do something to that response or run any needed code.
 - Then it returns the response.

Example:

```python
import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware(&quot;http&quot;)
async def add_process_time_header(request: Request, call_next):
    # do things before the request
    response = await call_next(request)
    # do things after the response
    return response

references:

huangapple
  • 本文由 发表于 2023年2月17日 23:50:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定