FastAPI 环境安装- python 后端开发 02

安装 python 环境

请参照Python 开发环境搭建来安装 python 和 IDE,推荐使用 Virtual Studio Code, 本文将以此 IDE 来做演示。

pip 加速

默认情况下 pip 从国外网站下载软件包,下载速度过慢,我们需要给切换成国内的网站。配置方式如下:

# 使用本镜像站来升级 pip
pip install -i https://mirrors.ustc.edu.cn/pypi/web/simple pip -U
pip config set global.index-url https://mirrors.ustc.edu.cn/pypi/web/simple
复制代码

点击查看详细的配置方式

安装 poetry

poetry 是新的 python 依赖管理工具(相当于 Node.js 的 yarn / npm,ruby 的 bundler ),能够更方便的管理项目中的依赖,功能甩 pip 几条街。安装的方式也特别简单:

# 安装命令
pip install poetry
​
# 验证一下安装的版本
poetry --version
复制代码

接下来我们用 poetry 来创建一个新的项目 hello-py

poetry new hello-py 
​
cd hello-py
poetry install  # 安装依赖
复制代码

上面命令会在当前目录创建一个 hello-py, 打开目录看到以下结果:

poetry 项目文件结构

hello-py 是新建的一个 python module

tests 目录下面是单元测试代码

Screen Shot 2021-09-10 at 9.42.39 PM

参照上图,点击左侧的 Testing 图标,依次选择 Configure Python Tests > pytest > tests ,然后你就会看到所有的测试用例了。点击运行即可单独执行这一条用例。

Screen Shot 2021-09-10 at 9.44.03 PM

pyptroject.toml 是项目的配置文件,里面记录了项目的一些基本信息和所需要的依赖。

更多信息查看 poetry 的官方网站

安装 fastapi 依赖

上文中我们使用 pip 安装了依赖,本章我们使用 poetry 来管理。在 Terminal 中,切换到项目目录,然后执行:

poetry add fastapi uvicorn[standard]
# zsh 请使用   poetry add fastapi "uvicorn[standard]"
复制代码

poetry 安装结果

poetry 安装依赖的同时,会将依赖记录在 pyproject.toml 文件中。

编码咯

新建一个 main.py 文件,输入以下代码:

from fastapi import FastAPI
​
app = FastAPI()
​
@app.get('/')
def hello():
    return {"message": "Hello World"}
​
复制代码

在 IDE 中按 F5 键,在弹出框中选择 FastAPI 运行即可

Screen Shot 2021-09-10 at 10.08.27 PM

正常会看到以下结果

Screen Shot 2021-09-10 at 10.09.50 PM

浏览器中输入 http://127.0.0.1:8000,即可看到运行结果

浏览器中输入 http://127.0.0.1:8000/docs, 即可看到 swagger 文档,简单加愉快。

Screen Shot 2021-09-10 at 10.14.24 PM

浏览器中输入http://127.0.0.1:8000/redoc,即可看到 redoc 格式文档。

Screen Shot 2021-09-10 at 10.14.19 PM

文件修改自动重启服务

Run 菜单中选择 Add Configuration...如果有弹出窗口,依次选择 Python > FastAPI),会生成一个 launcher.json文件,

Screen Shot 2021-09-10 at 10.22.16 PM

args 增加一行 --reload,最终配置文件如下。 这样在有文件修改的时候就可以自动重启了。

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: FastAPI",
      "type": "python",
      "request": "launch",
      "module": "uvicorn",
      "args": [
        "main:app",
        "--reload",   // 增加这一行
      ],
      "jinja": true
    }
  ]
}
复制代码

如果是 PyCharm 用户的话,在 main.py 添加 uvicorn.run() 即可,完整代码如下:

from fastapi import FastAPI
​
app = FastAPI()
​
​
@app.get('/')
def hello():
    return {"message": "Hello World"}
​
​
if __name__ == '__main__':
    import uvicorn
    uvicorn.run('main:app', reload=True)  #reload 会在文件有修改时,自动重启服务
​
复制代码

然后执行该文件即可

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享