【问题标题】:TypeError: object str can't be used in 'await' expression in FastAPI Middleware [duplicate]TypeError:对象 str 不能用于 FastAPI 中间件中的 \'await\' 表达式 [重复]
【发布时间】:2023-02-10 14:45:11
【问题描述】:
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.routing import Mount
from fastapi import FastAPI, HTTPException

class CustomHeaderMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next):
         customer =stripe.Customer.retrieve(request.session.get("user"))
         r= stripe.Subscription.list(customer=customer.id,limit=3)
         if r.data[0].status =="incomplete":
            raise HTTPException(401)
        #  response= RedirectResponse(url='/gradio')
         
         response = await call_next(request)
        
         return response  
 
io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")

middleware = [
    Middleware(CustomHeaderMiddleware)
]

routes = [
    Mount('/gradio', app=io, middleware=middleware),
]
app = FastAPI(routes=routes)

文件“C:\Users\Shivam 112\AppData\Roaming\Python\Python310\site-packages\starlette\middleware\base.py”,第 69 行,coro 等待 self.app(范围,receive_or_disconnect,send_no_error)

类型错误:对象 str 不能用于“等待”表达式

【问题讨论】:

标签: python fastapi middleware starlette


【解决方案1】:

这里的问题是 FastAPI 构造函数中的 routes 参数不接受普通的 Starlette 路由。可能有一种方法可以解决这个问题,但还有一个更简单的解决方案。仔细查看gradio,结果发现他们的网络应用程序一个FastAPI应用程序,这意味着我们可以add the middleware in the normal way,然后是mount the gradio app as a sub application

import gradio
import gradio.routes
import stripe
from fastapi import FastAPI, Request, Response, status
from starlette.middleware.base import BaseHTTPMiddleware


class CustomHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        customer = stripe.Customer.retrieve(request.session.get("user"))
        r= stripe.Subscription.list(customer=customer.id,limit=3)
        if r.data[0].status =="incomplete":
            return Response(status_code=status.HTTP_401_UNAUTHORIZED)

        response = await call_next(request)
        return response

io = gradio.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")

# Create gradio FastAPI application
gradio_app = gradio.routes.App.create_app(io)
gradio_app.add_middleware(CustomHeaderMiddleware)

app = FastAPI()

app.mount("/gradio", gradio_app)

此外,引发 HTTPException 仅适用于 FastAPI 路由,不适用于中间件,这就是为什么我返回一个简单的响应。

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多