Severless-Flask 后端api部署

67 阅读2分钟

项目简介:
根据特定条件筛选出中国农业大学课程列表

首先是喜闻乐见的前端部分

<script setup lang="ts">
  import { NButton, NCard, NInput, NSpace, NDataTable } from 'naive-ui';
  import axios from 'axios';
  import { reactive, ref } from 'vue';
  const course = reactive({
    searchName: '',
    searchTeacher: '',
  });
  const data = ref([] as any);

  function search() {
    const params = new URLSearchParams();
    if (course.searchTeacher) {
      params.append('teacher_name', course.searchTeacher);
    }
    // 使用axios发送GET请求
    axios
      .get('https://flask-ogbkirecqx.cn-hangzhou.fcapp.run/search', {
        params: params,
      })
      .then((res) => {
        // 在处理响应之前,先打印整个响应对象
        console.log('Response:', res.data);

        // 假设响应数据是一个课程对象的数组
        data.value = res.data; // 直接将响应数据赋值给 data.value
      })
      .catch((error) => {
        console.error('Error fetching the search results:', error);
      });
  }

  interface Column {
    title: string;
    key: string;
    width: number;
    fixed?: 'left' | 'right';
  }
  const columns: Column[] = [
    {
      title: '课程名称',
      key: 'name',
      fixed: 'left',
      width: 50,
    },
    {
      title: '校区',
      key: 'campus',
      width: 33,
    },
    {
      title: '授课教师',
      key: 'teacher',
      width: 40,
    },
    {
      title: '授课时间',
      key: 'time',
      width: 60,
    },
    {
      title: '授课地点',
      key: 'location',
      width: 40,
    },
    {
      title: '班级',
      key: 'clazz',
      width: 40,
    },
    {
      title: '排课人数',
      key: 'size',
      width: 40,
    },
    {
      title: '选课人数',
      key: 'number',
      width: 40,
    },
  ];

  const width = window.innerWidth;
</script>

<template>
  <div class="container">
    <n-card title="课程 | Course">
      <n-space vertical>
        <div>授课老师</div>
        <n-input
          v-model:value="course.searchTeacher"
          placeholder="请输入授课老师(支持模糊搜索)"
          maxlength="42"
          ></n-input>
        <n-button ghost block @click="search()" :loading="course.loading">检索</n-button>
      </n-space>
    </n-card>
    <n-data-table :columns="columns" :data="data" size="small" striped :scroll-x="800" :pagination="{}" />
  </div>
</template>

<style scoped>
  .container {
  max-width: 880px;
  margin: auto;
  }
</style>

然后是采用 Flask 框架的后端代码

from flask import Flask, jsonify, request
import os
import json

app = Flask(__name__)

@app.route('/search', methods=['GET'])
def search():
    # 获取查询参数
    teacher_name = request.args.get('teacher_name', '')

    # 获取model.json文件的路径
    current_dir = os.path.dirname(__file__)  # 获取当前文件夹的路径
    json_file_path = os.path.join(current_dir, 'model.json')  # 构建model.json的完整路径

    # 初始化结果列表
    results = []

    # 从model.json中读取数据
    with open(json_file_path, 'r', encoding='utf-8') as f:
        courses = json.load(f)  # 假设model.json文件的结构是一个课程列表

    # 对每个课程进行模糊搜索
    for course in courses:
        # 检查课程名称或教师姓名是否包含查询字符串
        if teacher_name.lower() in course['teacher'].lower():
            results.append(course)

    # 返回搜索结果
    return jsonify(results), 200, {'Content-Type': 'application/json; charset=utf-8'}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)

数据集:中国农业大学课程列表

model.json

最后是部署及测试啦(以阿里云为例)

创建触发器
使用在线工具进行测试