FastAPI路由函数调用其他函数会返回响应,给出示例
时间: 2024-01-04 20:02:27 浏览: 33
当你在FastAPI中定义一个路由函数时,你可以在函数内部调用其他函数,然后将函数的返回值作为响应返回给客户端。下面是一个简单的示例:
```python
from fastapi import FastAPI
app = FastAPI()
def calculate_sum(a: int, b: int) -> int:
return a + b
@app.get("/{a}/{b}")
async def sum(a: int, b: int):
result = calculate_sum(a, b)
return {"result": result}
```
在上面的示例中,我们定义了一个计算两个数之和的函数`calculate_sum()`,然后在路由函数`sum()`中调用该函数进行计算。最终,我们将计算结果作为字典对象`{"result": result}`返回给客户端。
当客户端发送GET请求并提供两个参数`a`和`b`时,FastAPI会自动将这两个参数解析为整数类型,并传递给路由函数`sum()`作为参数。在路由函数内部,我们调用`calculate_sum()`函数进行计算,并将计算结果作为字典对象返回给客户端。FastAPI会自动将字典对象转换为JSON格式并设置Content-Type头为application/json。
相关问题
FastAPI 在调用函数返回响应,给出示例
当你在FastAPI中定义一个路由函数时,你可以在函数内部使用Python的return语句来返回数据,FastAPI会自动将其转换为响应并返回给客户端。下面是一个简单的示例:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello, World!"}
```
在上面的示例中,我们定义了一个根路由`/`,当客户端发送GET请求到该路由时,我们返回一个字典对象`{"message": "Hello, World!"}`。FastAPI会自动将其转换为JSON格式并设置Content-Type头为application/json。
你也可以返回一个字符串,例如:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return "Hello, World!"
```
在上面的示例中,我们直接返回了一个字符串`"Hello, World!"`,FastAPI会将其设置为响应正文并设置Content-Type头为text/plain。
fastapi 异步调用
使用 FastAPI 进行异步调用需要使用 Python 的异步特性,例如使用 async/await 关键字和 asyncio 库。以下是使用 FastAPI 进行异步调用的示例代码:
```python
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import httpx
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
async def root():
async with httpx.AsyncClient() as client:
response = await client.get("https://www.example.com")
return response.text
```
在这个示例中,我们使用了 httpx 库进行异步 HTTP 请求,并在 FastAPI 的路由函数中使用了 async/await 关键字。为了启用异步支持,我们将返回的响应类型设置为 HTMLResponse,并将函数定义为 async。
除了使用异步库外,还可以使用 FastAPI 内置的异步支持。例如,使用 asyncpg 库进行异步 PostgreSQL 数据库访问的示例代码如下:
```python
import asyncpg
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup():
app.state.pool = await asyncpg.create_pool("postgresql://user:password@localhost/dbname")
@app.get("/")
async def read_root():
async with app.state.pool.acquire() as connection:
result = await connection.fetch("SELECT 1")
return {"result": result}
```
在这个示例中,我们在 FastAPI 的应用程序启动事件中创建了一个异步 PostgreSQL 连接池,并在路由函数中使用了 async/await 关键字进行异步查询。