FastAPI构建后端

目录

前言

一、FastAPI是什么?

二、基本概念

三、创建第一个FastAPI后端


前言

使用FastAPI构建后端


一、FastAPI是什么?

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,专为在 Python 中构建 RESTful API 而设计。

二、基本概念

FastAPI是一个后端框架,使用py代码编写后端,对前端的请求进行响应,在前端显示出对应的内容。

三、创建第一个FastAPI后端

基本的FastAPI代码:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}
  1. 注意,需要导入FastAPI包,pip install FastAPI
  2. 然后使用FastAPI类,创建一个类对象
  3. 编写后端响应:@app.get(“/”)是装饰器,”/”表示根目录,get是请求类型除了get还有post、put、delete、patch、options、head
  4. 启动本地服务,在终端输入uvicorn main:app --reload,如果uvicorn指令,无效检查是否安装FastAPI包,是否激活py环境,是否设置环境变量等原因
  5. 在浏览器访问127.0.0.1:8000,默认的是8000端口
  6. 可以设置别的端口,uvicorn main:app --host 127.0.0.1 --port 8080 --reload
     

四、在前端展示一个html界面

  1. 设置路由
    from fastapi import FastAPI
    from fastapi.responses import HTMLResponse, JSONResponse
    import json
    
    app = FastAPI()
    
    
    @app.get("/", response_class=HTMLResponse)
    def dapin():
        with open("graph.html", "r", encoding="utf-8") as f:
            contents = f.read()
            return contents
    
    
    @app.get("/json")
    def getdata():
        with open("les-miserables.json", "r", encoding="utf-8") as json_file:
            contents = json.load(json_file)
            return JSONResponse(content=contents)
    
  2. 配置文件graph.html和les-miserables.json
    <!--
    	此示例下载自 https://echarts.apache.org/examples/zh/editor.html?c=graph
    -->
    <!DOCTYPE html>
    <html lang="en" style="height: 100%">
    <head>
      <meta charset="utf-8">
    </head>
    <body style="height: 100%; margin: 0">
      <div id="container" style="height: 100%"></div>
    
      <script type="text/javascript" src="https://registry.npmmirror.com/jquery/3.7.1/files/dist/jquery.min.js"></script>
      <script type="text/javascript" src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/echarts.min.js"></script>
    
      <script type="text/javascript">
        var dom = document.getElementById('container');
        var myChart = echarts.init(dom, null, {
          renderer: 'canvas',
          useDirtyRect: false
        });
        var app = {};
        var ROOT_PATH = 'http://127.0.0.1:8000';
        var option;
    
        myChart.showLoading();
    $.getJSON(ROOT_PATH + '/json', function (graph) {
      myChart.hideLoading();
      graph.nodes.forEach(function (node) {
        node.label = {
          show: node.symbolSize > 30
        };
      });
      option = {
        title: {
          text: 'Les Miserables',
          subtext: 'Default layout',
          top: 'bottom',
          left: 'right'
        },
        tooltip: {},
        legend: [
          {
            // selectedMode: 'single',
            data: graph.categories.map(function (a) {
              return a.name;
            })
          }
        ],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            name: 'Les Miserables',
            type: 'graph',
            legendHoverLink: false,
            layout: 'none',
            data: graph.nodes,
            links: graph.links,
            categories: graph.categories,
            roam: true,
            label: {
              position: 'right',
              formatter: '{b}'
            },
            lineStyle: {
              color: 'source',
              curveness: 0.3
            },
            emphasis: {
              focus: 'adjacency',
              lineStyle: {
                width: 10
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    });
    
        if (option && typeof option === 'object') {
          myChart.setOption(option);
        }
    
        window.addEventListener('resize', myChart.resize);
      </script>
    </body>
    </html>

    此处爬取les-miserables.json

    import requests
    import os
    
    url = "https://echarts.apache.org/examples/data/asset/data/les-miserables.json"
    file_path = os.path.join("les-miserables.json")
    response = requests.get(url)
    if response.status_code == 200:
        with open(file_path, "wb") as f:
            f.write(response.content)
    

    文件都放在同级目录,效果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值