只需执行: uvicorn zhiliao:app --host 0.0.0.0 --port 8080 --ssl-keyfile /ssl/private.key --ssl-certfile /ssl/certificate.crt 这意味着我们的应用将会在8080端口运行,并且暴露在公网中,人们都可以访问,--ssl-keyfile参数后面跟key文件目录,--ssl-certfile,同理。可以看到,网站已经可以用https访问。 3...
add_event_handler("shutdown", shutdown) @app.get("/") async def demo(): return {"name":"ok"} if __name__ == '__main__': uvicorn.run(app, host="127.0.0.1", port=8000) 接收文件上传 from fastapi import FastAPI, File, UploadFile, Form from fastapi.middleware.cors import CORS...
app=FastAPI() app.add_middleware(EventHandlerASGIMiddleware, handlers=[local_handler])# registering handler(s) @app.get("/") defindex(request:Request)->JSONResponse: dispatch("my-fancy-event",payload={"id":1})# Emit events anywhere in your code returnJSONResponse() 自定义handler 处理 from...
app = FastAPI()asyncdefstartup_event():print("Application has started.")asyncdefshutdown_event():print("Application is shutting down.") app.add_event_handler("startup", startup_event) app.add_event_handler("shutdown", shutdown_event) db_config = {'connections': {'default': {'engine'...
from fastapi_events.handlers.local import local_handler app = FastAPI() app.add_middleware(EventHandlerASGIMiddleware, handlers=[local_handler]) # registering handler(s) @app.get("/") def index(request: Request) -> JSONResponse: dispatch("my-fancy-event", payload={"id": 1}) # Emit event...
add_exception_handlers=True, ): # 数据库连接 yield # 应用清理完成 main_app = FastAPI(lifespan=lifespan) 所以利用这个方法,启动时的任务会在yield前插入,而关闭时的任务会在yield后插入。这是一个相当巧妙的想法。比如,我在应用程序启动时注册了Tortoise ORM。移除是自动的,因此无需执行任何关闭操作。
fromfastapiimportFastAPIapp=FastAPI()@app.on_event("shutdown")defshutdown_event():withopen("log.txt",mode="a")aslog:log.write("Application shutdown")@app.get("/items/")asyncdefread_items():return[{"name":"Foo"}] Here, theshutdownevent handler function will write a text line"Applicat...
app.add_exception_handler(未登录异常, 未登录处理函数) 所以现在我们的依赖关系抛出了 NotLoggedInException。FastAPI 捕捉到异常,然后运行 no_logged_in_handler()。进而让用户跳转到登录页面。 所以我们现在可以编写一系列的依赖关系、自定义异常和异常处理程序,来处理我们的认证和权限验证。 from auth.exceptions im...
app.add_exception_handler(Exception, python_exception_handler) @app.on_event("startup") async def startup_event(): """ Initialize FastAPI and add variables """ logger.info('Running envirnoment: {}'.format(CONFIG['ENV'])) logger.info('PyTorch using device: {}'.format(CONFIG['DEVICE']...
add_event_handler * 这个方法也可以添加 handler,只不过只能处理启动与关闭,其使用示例如下, fromfastapiimportFastAPIapp=FastAPI()# 定义启动事件defstartup_event():print("App is starting up!")# 定义关闭事件defshutdown_event():print("App is shutting down!")# 使用 add_event_handler 添加事件app.add...