我想在dependencies中使用,但是代码标黄了
时间: 2024-03-18 22:42:07 浏览: 19
在使用依赖项函数时,需要将依赖项函数传递给 `Depends()` 函数,并在 `Depends()` 函数中传递依赖项函数所需的参数。在你的代码中,如果要将依赖项函数 `ip_limiter()` 添加到路径操作函数的依赖项中,并传递 `hits` 和 `time` 参数,可以像下面这样写:
```python
from fastapi import Depends, FastAPI, Request
app = FastAPI()
async def ip_limiter(hits: int, time: str, request: Request = None):
print(hits, time)
if request:
try:
host = request.headers["x-real-ip"]
except:
host = request.client.host
data = {"hit": "10", "hits": "50", "ex": "2023-04-15 10:01:18.331799", "ip": host}
await request.app.state.cache.hmset('/init', data)
values = await request.app.state.cache.hgetall('/init1111')
print(values)
return True
@app.get("/")
async def root(limiter: bool = Depends(ip_limiter(hits=10, time="2022-05-01"))):
return {"message": "Hello World"}
```
在上面的代码中,我们将依赖项函数 `ip_limiter()` 传递给 `Depends()` 函数,并在 `Depends()` 函数中传递 `hits=10` 和 `time="2022-05-01"` 作为参数。注意,当我们将依赖项函数传递给 `Depends()` 函数时,函数名后面不需要加括号。
如果你的代码中出现了标黄,可能是因为 PyCharm 没有正确识别 FastAPI 的依赖项语法。你可以尝试更新 PyCharm 或者将 `Depends()` 函数中的依赖项函数的调用拆分成两行,如下所示:
```python
limiter_dependency = Depends(ip_limiter(hits=10, time="2022-05-01"))
@app.get("/")
async def root(limiter: bool = limiter_dependency):
return {"message": "Hello World"}
```
这样可以避免 PyCharm 对语法的识别问题。