使用fastapi写一个http接口

一,使用工具:FastAPI和uvicorn

通常我们写一个简单的http接口时常用flask,这次用点不一样的。
FastAPI是一个快速(高性能)的Web框架,需Python 3.6以上,安装方法:pip install fastapi
uvicorn是一个基于asyncio开发的一个轻量级高效的web服务器框架。需python3.5.3以上,安装方法:pip install uvicorn

二,get接口

# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2020/07/10 20:27
# @author  : LanBingWa
# @function: get service of fastapi

from fastapi import FastAPI
import uvicorn


app = FastAPI()


@app.get('/test/a={a}/b={b}')
def calculate(a: int = None, b: int = None):
    c = a + b
    res = {"res": c}
    return res


if __name__ == '__main__':
    uvicorn.run(app=app,
                host="0.0.0.0",
                port=8080,
                workers=1)

浏览器访问接口:http://127.0.0.1:8080/test/a=3/b=8
在这里插入图片描述

三,post接口

# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2020/07/10 20:43
# @author  : LanBingWa
# @function: post service of fastapi

from pydantic import BaseModel
from fastapi import FastAPI
import uvicorn


app = FastAPI()


class Item(BaseModel):
    a: int = None
    b: int = None


@app.post('/test')
def calculate(request_data: Item):
    a = request_data.a
    b = request_data.b
    c = a + b
    res = {"res": c}
    return res


if __name__ == '__main__':
    uvicorn.run(app=app,
                host="0.0.0.0",
                port=8080,
                workers=1)

浏览器访问接口:http://127.0.0.1:8080/test
在这里插入图片描述

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值