使用APIRouter路由子模块功能

问题描述 投票:0回答:2

我的

main.py
中有以下内容:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from my_app.web.views import default

app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=500)
app.include_router(default.router)
#app.include_router(data_mgr_view.router)

app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/templates", Jinja2Templates(directory="templates"), name="templates")


@app.get('/test')
async def test():
    return "test successful"

这个效果很好。我可以点击

localhost:5000/test
处的 URL,它会返回预期的字符串。 现在我有了这个文件
default.py
我想将其处理程序基于根目录:

import sys, traceback
import pandas as pd
from fastapi import APIRouter, Request, Query
from my_app.web.models.response_data import ResponseData
from my_app.data.providers.internals_provider import MktInternalsProvider
from my_app.config import tmplts

router = APIRouter(prefix="")

@router.route('/')
async def root(request: Request):
    context = {"title":"Playground", "content":f"Place for my charts, studies, etc..."}
    return tmplts.TemplateResponse(request=request, name="index.html", context=context)

@router.route('/test2')
async def test2():
    return "test2 success"

当我点击

localhost:5000/
时,第一种方法效果很好。当我点击
localhost:5000/test2
:

时,第二种方法会抛出异常
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 411, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 69, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/applications.py", line 123, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/middleware/errors.py", line 186, in __call__
    raise exc
  File "/usr/local/lib/python3.11/site-packages/starlette/middleware/errors.py", line 164, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.11/site-packages/starlette/middleware/gzip.py", line 24, in __call__
    await responder(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/middleware/gzip.py", line 44, in __call__
    await self.app(scope, receive, self.send_with_gzip)
  File "/usr/local/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 65, in __call__
    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app
    raise exc
  File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
    await app(scope, receive, sender)
  File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 756, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 776, in app
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 297, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 77, in app
    await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app
    raise exc
  File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
    await app(scope, receive, sender)
  File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 72, in app
    response = await func(request)
                     ^^^^^^^^^^^^^
TypeError: test2() takes 0 positional arguments but 1 was given
python fastapi starlette
2个回答
1
投票

当使用

APIRouter
(也请参阅
APIRouter
类文档
)时,您不应该使用
route
装饰器/方法(顺便说一句,它在 Starlette 的源代码中似乎已被弃用) ,不鼓励使用)。

您应该使用

api_route
装饰器。示例:

from fastapi import FastAPI
from fastapi import APIRouter

router = APIRouter()

@router.api_route('/')
async def root():
    return {"op": "root"}

    
app = FastAPI()
app.include_router(router)

该装饰器允许的默认 HTTP 方法是

GET
,但您可以根据需要使用装饰器中的
methods
参数来自定义它。示例:

@router.api_route('/', methods=["GET", "POST"])

或者,您可以像往常一样简单地使用

@router.get
@router.post
等装饰器。示例:

@router.get('/')
@router.post('/')

我强烈建议您查看这个答案这个答案,以及这个答案这个答案,它们与主题相关,应该会有所帮助。


0
投票

这会起作用: 提供带有路由器的方法,如

get
post

@router.get('/test2')
async def test2():
    return "test2 success"
© www.soinside.com 2019 - 2024. All rights reserved.