{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 如何在 Jupyter 中运行 FastAPI 应用程序" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 在 Jupyter 中运行 FastAPI 应用程序\n", "要在 Jupyter 中运行 FastAPI 应用程序,我们可以使用以下命令:\n", "\n", "```python\n", "if __name__ == \"__main__\":\n", " import uvicorn\n", " uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在上面的代码中,使用 {func}`uvicorn.run` 函数来运行 FastAPI 应用程序。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 使用 Jupyter 内嵌窗口运行 FastAPI 应用程序" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "如果您希望从已经运行的 `async` 环境中运行 `uvicorn`,请改用 `uvicorn.Server.serve()` (将以下代码添加到您的 Jupyter 笔记本中的新代码单元格中并执行它):\n", "\n", "```python\n", "import asyncio\n", "import uvicorn\n", "\n", "if __name__ == \"__main__\":\n", " config = uvicorn.Config(app)\n", " server = uvicorn.Server(config)\n", " await server.serve()\n", "```\n", "\n", "或者,获取当前事件循环(使用 `asyncio.get_event_loop()`),并调用 `loop.create_task()` 在事件循环内为当前线程创建任务:\n", "```python\n", "import asyncio\n", "import uvicorn\n", "\n", "if __name__ == \"__main__\":\n", " config = uvicorn.Config(app)\n", " server = uvicorn.Server(config)\n", " loop = asyncio.get_event_loop()\n", " loop.create_task(server.serve())\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "ai", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.9" } }, "nbformat": 4, "nbformat_minor": 2 }