用Python快速实现RestfulAPI

RestfulAPI是一种REST风格的API,因为它具有结构清晰、符合标准、易于理解、扩展方便等特点而被越来越多的网站采用。

简介

这里采用了FastApi框架,根据官方的描述,FastApi是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用基于类型提示的 Python 3.6 及更高版本。当然,这个框架的性能还是不错的,上手也是非常的容易。

安装

1
pip install fastapi uvicorn

示例

基本使用async def

1
2
3
4
5
6
7
8
9
10
11
12
13
# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
return {"Hello": "World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

然后在终端输入指令,就可以运行了。

1
uvicorn main:app --reload

你可以在/下得到{"Hello":"World"}的JSON响应,在/items/1?q=demo下得到{"item_id": 1, "q": "demo"}的JSON响应。

连接MySQL数据库

这里使用到了batabases,它提供了一系列数据库的简单的Asyncio支持。

1
pip install databases

只需要在main.py中加入以下几行代码,就可以在使用数据库的自动开启和关闭。

1
2
3
4
5
6
7
8
9
10
11
12
13
# main.py
from .config import db

# 自动开启数据库
@app.on_event('startup')
async def startup():
await db.connect()


# 关闭数据库
@app.on_event("shutdown")
async def shutdown():
await db.disconnect()

config.py

1
2
3
4
5
6
7
8
9
10
11
from databases import Database

# ----------数据库参数设置----------
user_name = "your_username"
password = "your_password"
host = "xxx.xxx.xxx.xx"
database_name = "your_databsename"
# 数据库配置基本信息
Database_URL = f'mysql://{user_name}:{password}@{host}/{database_name}?charset=utf8mb'

db = Database(Database_URL)

具体使用方法参考官方文档。

碎碎言

因为用Python实现一个功能比较健全的后端API,避免不了安装许多的依赖包,像之前使用的flask,就需要通过生成reqiurements.txt来实现依赖包的汇总,以便能够进行环境的迁移。但是,最近我发现了一个不错的Python依赖包管理工具—poetry,具体用法可以参考官方文档。