一、FastAPI框架

1. 什么是FastAPI

FastAPI是一个现代的,快速(高性能)python web框架. 基于标准的python类型提示,使用python3.6+构建API的Web框架.

简单讲FastAPI就是把做web开发所需的相关代码全部简化, 我们不需要自己实现各种复杂的代码, 例如多任务,路由装饰器等等. 只需要调用FastAPI提供给我们的函数, 一调用就可以实现之前需要很多复杂代码才能实现的功能.

FastAPI的特点

· 性能快:高性能,可以和NodeJS和Go相提并论· 快速开发:开发功能速度提高约200%至300%· 更少的Bug:· Fewer bugs: 减少40%开发人员容易引发的错误· 直观:完美的编辑支持· 简单: 易于使用和学习,减少阅读文档的时间· 代码简洁:很大程度上减少代码重复。每个参数可以声明多个功能,减少bug的发生· 标准化:基于并完全兼容API的开发标准:OpenAPI(以前称为Swagger)和JSON Schema 搭建环境

python环境:Python 3.6+ fastapi安装

安装方式1:

安装fastapi

pip install fastapi如果用于生产,那么你还需要一个ASGI服务器,如Uvicorn或Hypercorn

pip install uvicorn 安装方式2 : 1) 选择File->Settings

​ 2)选择对应项目的Project Interpreter -> 选择pygame(可以输入pygame进行搜索,节省时间) -> install package按钮 -> 等待项目安装pygame 包完成(可能需要几分钟到十几分钟)-> 返回后如果有pygame package信息,则说明项目配置成功

2. FastAPI的基本使用

功能需求:

搭建服务器返回html页面

基本步骤:

导入模块创建FastAPI框架对象通过@app路由装饰器收发数据运行服务器

代码实现:

# 导入FastAPI模块

from fastapi import FastAPI

# 导入响应报文Response模块

from fastapi import Response

# 导入服务器uvicorn模块

import uvicorn

# 创建FastAPI框架对象

app = FastAPI()

# 通过@app路由装饰器收发数据

# @app.get(参数) : 按照get方式接受请求数据

# 请求资源的 url 路径

@app.get("/index.html")

def main():

with open("source/html/index.html") as f:

data = f.read()

# return 返回响应数据

# Response(content=data, media_type="text/html"

# 参数1: 响应数据

# 参数2: 数据格式

return Response(content=data, media_type="text/html")

# 运行服务器

# 参数1: 框架对象

# 参数2: IP地址

# 参数3: 端口号

uvicorn.run(app, host="127.0.0.1", port=8000)

3. 通过FastAPI访问多个指定网页

路由装饰器的作用: 实际上通过路由装饰器我们就可以让一个网页对应一个函数, 也就可以实现访问指定网页了.

# 导入FastAPI模块

from fastapi import FastAPI

# 导入响应报文Response模块

from fastapi import Response

# 导入服务器uvicorn模块

import uvicorn

# 创建FastAPI框架对象

app = FastAPI()

# 通过@app路由装饰器收发数据

# @app.get(参数) : 按照get方式接受请求数据

# 请求资源的 url 路径

@app.get("/index1.html")

def main():

with open("source/html/index1.html") as f:

data = f.read()

# return 返回响应数据

# Response(content=data, media_type="text/html"

# 参数1: 响应数据

# 参数2: 数据格式

return Response(content=data, media_type="text/html")

@app.get("/index2.html")

def main():

with open("source/html/index2.html") as f:

data = f.read()

# return 返回响应数据

# Response(content=data, media_type="text/html"

# 参数1: 响应数据

# 参数2: 数据格式

return Response(content=data, media_type="text/html")

# 运行服务器

# 参数1: 框架对象

# 参数2: IP地址

# 参数3: 端口号

uvicorn.run(app, host="127.0.0.1", port=8000)

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: