2022-01-05 fastapi框架

fastapi框架

浏览器与服务器交互过程
在这里插入图片描述

fastapi运行流程
  • 第一步在浏览器上输入我们需要访问的url,浏览器会发送一个get请求给服务器;
  • 第二步,服务器在接受到浏览器发来的get请求后,会被@app路由装饰器捕获并返回相应的请求资源;
  • 第三步,浏览器在接收到相应的页面资源后,会根据页面内容再次请求页面所需的资源,如图片0.jpg;
  • 第四步,服务器重复第二步,返回请求资源

一、安装fastapi
pip install uvicorn

pip install fastapi

二、fastapi框架搭建
导入模块->创建fastapp框架对象->@app路由装饰器收发数据->运行服务器
from fastapi import FastAPI
from fastapi import Response
import uvicorn

#创建fastapp框架对象
app=FastAPI()

#@app路由装饰器收发数据
@app.get("/render.html")
def func01():
    with open("./html/html/render.html", "rb") as f:
        file_data = f.read()
    return Response(content=file_data,media_type="text/html")

@app.get("/gdp.html")
def func02():
    with open("./html/html/gdp.html", "rb") as f:
        file_data = f.read()
    return Response(content=file_data,media_type="text/html")

#运行服务器
uvicorn.run(app,host="127.0.0.1",port=8080)

三、fastapi通用配置
通用配置:(可以省去带量的重复代码的书写)
from fastapi import FastAPI
from fastapi import Response
import uvicorn

#创建fastapp框架对象
app=FastAPI()

#@app路由装饰器收发数据
# path相当于一个参数 当浏览器访问服务器的时候会把响应请求路径给到path
# path==> xxx.html
@app.get("/{path}")
# 这指定了函数的参数类型为str字符串类型
def func01(path:str):
    with open(f"./html/html/{path}", "rb") as f:
        file_data = f.read()
    return Response(content=file_data,media_type="text/html")

#path ==> xxx.jpg
@app.get("/images/{path}")
def func02(path: str):
    with open(f"./images/{path}", "rb") as f:
        file_data = f.read()
    return Response(content=file_data,media_type="jpg")

#运行服务器
uvicorn.run(app,host="127.0.0.1",port=8080)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向岸看

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值