Jack's Studio.

fastapi学习篇

字数统计: 478阅读时长: 2 min
2025/03/13
loading

针对python的web框架的fastapi的学习应用。

环境准备

fastapi是比较新的一个web框架,所以对于python版本依赖也比较高,使用要注意这点。准备python项目中重要的虚拟环境,这里使用pipenv来进行操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$ sudo pip install pipenv
$ mkdir fastPra && cd fastPra
# 开始创建虚拟环境
/tutorial/fastPra$ pipenv shell
# ok
(fastPra)/tutorial/fastPra$ ls
Pipfile
(fastPra)/tutorial/fastPra$ pip install fastapi
(fastPra)/tutorial/fastPra$ pipenv graph
fastapi==0.115.11
├── pydantic
│ ├── annotated-types
│ ├── pydantic_core
│ │ └── typing_extensions
│ └── typing_extensions
├── starlette
│ └── anyio
│ ├── idna
│ ├── sniffio
│ └── typing_extensions
└── typing_extensions
(fastPra)/tutorial/fastPra$ deactivate
$ pipenv shell
Launching subshell in virtual environment...
gemini@gemini:~/tutorial/fastPra$ source /home/gemini/.local/share/virtualenvs/fastPra-mVLq17Hw/bin/activate
(fastPra)/tutorial/fastPra$

环境准备完毕,开造。

一、action

fastapi是针对restful类型api构建的一个web框架,所以它在创建完成fastapi的应用后,就会对应自动生成api文档,而且它支持异步,这点和flask以及django都不太一样。

1.1 创建第一个fastapi应用

直接创建app.py,编辑如下:

1
2
3
4
5
6
7
8
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def index():
return "Hello, world.\n"

嗯,运行一下:

1
2
(fastPra)/tutorial/fastPra$ python app.py
(fastPra)/tutorial/fastPra$

嗯?没了?好像不对哎。好吧,fastapi没有内置服务器,所以需要引入一个asgi服务器或者wsgi好像也行。

1
2
3
4
5
6
7
8
9
(fastPra)/tutorial/fastPra$ pip install uvicorn
(fastPra)/tutorial/fastPra$ uvicorn app:app --reload
INFO: Will watch for changes in these directories: ['/home/jack/personal-projects/tutorial/fastPra']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [52484] using StatReload
INFO: Started server process [52486]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:34162 - "GET / HTTP/1.1" 200 OK

如上,服务运行于http://localhost:8000/,新开一个终端curl一下:

1
2
$ curl http://localhost:8000/
"Hello, world.\n"$

嗯,好像和预料的不一样,还是太习惯flask了。浏览器访问一下http://localhost:8000/docs,就可以看到自动生成的api文档了(这功能是通过Swagger来实现的,很多web框架都用它来进行api文档生成):

CATALOG
  1. 环境准备
  2. 一、action
    1. 1.1 创建第一个fastapi应用