FastAPI 如何在文件更改时重新加载 FastAPI 应用程序
在本文中,我们将介绍如何使用FastAPI重新加载应用程序当除*.py文件之外的文件发生更改时。如果您正在使用FastAPI来构建Web应用程序,这对您来说将是一个非常有用的功能。
阅读更多:FastAPI 教程
使用Uvicorn监视文件更改
要实现文件更改时重新加载FastAPI应用程序的功能,我们可以借助Uvicorn来监视文件更改并自动重新启动应用程序。Uvicorn是一个快速的ASGI服务器,它是FastAPI的默认服务器。
首先,我们需要确保已经安装了Uvicorn。您可以使用以下命令在命令行中安装它:
$ pip install uvicorn
接下来,我们需要编写一个单独的脚本来启动FastAPI应用程序,并使用Uvicorn的自动重载功能。创建一个名为main.py
的文件,并将以下代码复制到文件中:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
然后,在同一目录下创建一个名为dev.sh
的文件,并将以下代码复制到文件中:
#!/usr/bin/env bash
uvicorn main:app --reload
现在,我们可以运行dev.sh
文件来启动FastAPI应用程序,并在文件更改时重新加载它。使用以下命令在终端中执行脚本:
$ bash dev.sh
示例说明
假设我们在FastAPI应用程序中有一个名为data.json
的文件,我们希望在该文件更改时重新加载应用程序。我们可以按照以下步骤进行操作:
- 在
main.py
中,添加一个名为watcher
的变量,用于监视文件的更改:
import os
from fastapi import FastAPI
from pydantic import BaseSettings
from uvicorn import run
app = FastAPI()
class Settings(BaseSettings):
data_file: str = "data.json"
settings = Settings()
class FileWatcher:
def __init__(self, filename):
self.filename = filename
self.timestamp = os.stat(self.filename).st_mtime
def check_changes(self):
new_timestamp = os.stat(self.filename).st_mtime
if new_timestamp > self.timestamp:
print(f"{self.filename} has changed")
self.timestamp = new_timestamp
return True
return False
watcher = FileWatcher(settings.data_file)
@app.get("/")
def read_root():
if watcher.check_changes():
# 重新加载数据
pass
return {"Hello": "World"}
- 然后,在
dev.sh
中添加一个定期检查文件更改的循环:
#!/usr/bin/env bash
while true; do
uvicorn main:app --reload
if [ -f watcher.py ]; then
python watcher.py
fi
done
现在,当data.json
文件发生更改时,FastAPI应用程序将自动重新加载,并重新加载数据。
总结
通过使用Uvicorn和自定义文件监视器,我们可以实现在文件更改时自动重新加载FastAPI应用程序的功能。这样一来,我们可以更加高效地开发和调试FastAPI应用程序,提高开发效率。希望本文对您有所帮助!