栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

fastAPI简单使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

fastAPI简单使用

目录
  • 前言
  • 一、fastAPI是什么?
  • 二、安装
    • 1.fastapi的安装(此处用的是阿里云镜像源)
    • 2.测试一下
  • 三、使用
    • 1.声明路径参数
    • 2. 声明路径参数有效值
    • 3. 声明路径参数为路径
    • 4. 声明params参数
    • 5. 请求体(如post请求会用到)


前言

利用python fastAPI框架搭建简便的api服务


一、fastAPI是什么?

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。总之它可以简单快捷的创建api服务。

二、安装 1.fastapi的安装(此处用的是阿里云镜像源)
pip install fastapi -i https://mirrors.aliyun.com/pypi/simple
pip install uvicorn -i https://mirrors.aliyun.com/pypi/simple
2.测试一下

创建文件test.py,代码如下:

from fastapi import FastAPI

app = FastAPI()


@app.get('/')
def main():
	return {"message": "hello"}

然后打开终端(wins + R)启动uvicorn服务: uvicorn test:app --reload
其中test 为文件名;app为test.py中创建的app对象;–reload为热启动,重启服务

看到如图结果代表启动成功。打开游览器输入127.0.0.1:8000/即可看到main方法中的输出结果。

三、使用 1.声明路径参数
from fastapi import FastAPI

app = FastAPI()


@app.get('/home/{key}')
def main(key):  # 在这里可以定义key的类型,例如int类型: def main(key: int)
	return {"key": key}
	

请求结果:

2. 声明路径参数有效值
from fastapi import FastAPI
from enum import Enum

app = FastAPI()


class limit(str, Enum):
    value1 = "111"
    value2 = "222"
    value3 = "333"


@app.get('/home/{key}')
def main(key: limit):
    return {"key": key}

超出限制范围的请求会返回告知你一个错误信息的json:

3. 声明路径参数为路径
from fastapi import FastAPI

app = FastAPI()


@app.get('/file/{file_path:file_path}')
def main(file_path):
	return {"path": file_path}
	
4. 声明params参数
from fastapi import FastAPI

app = FastAPI()


@app.get('/file')
def main(value1, value2):
	return {"value1": value1, "value2": value2}
	

使用浏览器访问http://127.0.0.1:8000/file?value1=ssss&value2=rrrrrrr,你会得到:{ "value1": "ssss", "value2": "rrrrrrr" }

5. 请求体(如post请求会用到)

定义请求体,需要使用 Pydantic

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


@app.get('/home')
def main(item: Item):
	return item


class Item(BaseModel):
    value1: str
    value2: str = None
    value3: float = None

用postman发送模拟post请求(请求体格式为json):

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号