百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

fastapi+vue3开发demo网站(vue3.0开发)

ztj100 2025-03-19 18:44 31 浏览 0 评论

通常demo网站很简单,是一个新手上车的第一步,今天我用 fastapi+vue3+mysql8 终于实现了demo网站的开发,记录整个过程,非常有实战价值,值得每一个新手学习。这里能学到几个知识,第一个就是前后端分离,解决跨域问题,然后就是http异步请求,提高并发。

网站是本地开发的,访问前端的127.0.0.1:8080/api/,会转发到后台的 127.0.0.1:8000/ ,功能非常简单,就是CURD,目前只有增删,没有改查,还不完善,提前抱出来让大家看看,回头继续学习。30+的年龄,向全栈进发,啥都要会一点。

1、在ubuntu上安装mysql-server端,并设置远程用户密码

sudo apt update
sudo apt install mysql-server
sudo service mysql start
sudo service mysql status
mysql --version
mysql -u root

# 版本小于8
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
CREATE USER 'ailx10'@'%' IDENTIFIED BY '123456';
# 版本大于8
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY '123456';
CREATE USER 'ailx10'@'%' IDENTIFIED WITH mysql_native_password BY '123456';

GRANT ALL PRIVILEGES ON *.* TO 'ailx10'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;
mysql -u root -p
# 输入密码 123456

2、修改mysqld的配置

/etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 0.0.0.0
service mysql restart

3、创建数据库,表,字段

CREATE DATABASE IF NOT EXISTS http;
USE http;
CREATE TABLE IF NOT EXISTS http_content (
    id INT AUTO_INCREMENT PRIMARY KEY,
    http_request TEXT NOT NULL,
    http_response TEXT NOT NULL,
    attack_result TEXT
);

4、后台开发

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import aiomysql

app = FastAPI()

# 启用跨域支持
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源访问,实际应根据需要配置
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有HTTP头部
)

# 数据库连接池
async def connect_to_database():
    pool = await aiomysql.create_pool(
        host='127.0.0.1',
        port=3306,
        user='ailx10',
        password='123456',
        db='http',
        autocommit=True
    )
    return pool

# 数据库模型
class Item(BaseModel):
    http_request: str
    http_response: str
    attack_result: str = None


# 获取数据
@app.get("/get_all_data")
async def get_all_data():
    pool = await connect_to_database()
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT * FROM http_content")
            data = await cur.fetchall()
            return [{"id": row[0], "http_request": row[1], "http_response": row[2], "attack_result": row[3]} for row in data]


# 标记攻击结果
@app.put("/mark_attack_result/{item_id}/{attack_result}")
async def mark_attack_result(item_id: int, attack_result: str):
    pool = await connect_to_database()
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(
                "UPDATE http_content SET attack_result = %s WHERE id = %s",
                (attack_result, item_id)
            )
            if cur.rowcount == 0:
                raise HTTPException(status_code=404, detail="Item not found")
            return {"message": f"Attack result for item ID {item_id} marked as {attack_result}"}

# 添加数据
@app.post("/add_item")
async def add_item(item: Item):
    pool = await connect_to_database()
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(
                "INSERT INTO http_content (http_request, http_response) VALUES (%s, %s)",
                (item.http_request, item.http_response)
            )
            return {"message": "Item added successfully"}

# 删除数据
@app.delete("/delete_item/{item_id}")
async def delete_item(item_id: int):
    pool = await connect_to_database()
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("DELETE FROM http_content WHERE id = %s", (item_id,))
            if cur.rowcount == 0:
                raise HTTPException(status_code=404, detail="Item not found")
            return {"message": f"Item ID {item_id} deleted successfully"}

5、前端开发

(1)HelloWorld.vue 文件


  
  <script>
  import axios from "axios";
  
  export default {
    data() {
      return {
        items: [],
        newItem: {
          http_request: "",
          http_response: "",
        },
      };
    },
    created() {
      this.getData();
    },
    methods: {
      async getData() {
        try {
          const response = await axios.get("/api/get_all_data");
          this.items = response.data;
        } catch (error) {
          console.error(error);
        }
      },
      async markAsSuccessful(id) {
        try {
          await axios.put(`/api/mark_attack_result/${id}/successful`);
          await this.getData();
        } catch (error) {
          console.error(error);
        }
      },
      async markAsFailed(id) {
        try {
          await axios.put(`/api/mark_attack_result/${id}/failed`);
          await this.getData();
        } catch (error) {
          console.error(error);
        }
      },
      async deleteItem(id) {
        try {
          await axios.delete(`/api/delete_item/${id}`);
          await this.getData();
        } catch (error) {
          console.error(error);
        }
      },
      async addItem() {
        try {
          await axios.post("/api/add_item", this.newItem);
          this.newItem = { http_request: "", http_response: "" };
          await this.getData();
        } catch (error) {
          console.error(error);
        }
      },
    },
  };
  </script>


(2)vue.config.js 文件

const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    open:true,        
    host:'127.0.0.1',        
    port:8080,        
    https:false,       
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/'
        }
      }
    }
  }
})

发布于 2024-01-12 19:22IP 属地北京

相关推荐

sharding-jdbc实现`分库分表`与`读写分离`

一、前言本文将基于以下环境整合...

三分钟了解mysql中主键、外键、非空、唯一、默认约束是什么

在数据库中,数据表是数据库中最重要、最基本的操作对象,是数据存储的基本单位。数据表被定义为列的集合,数据在表中是按照行和列的格式来存储的。每一行代表一条唯一的记录,每一列代表记录中的一个域。...

MySQL8行级锁_mysql如何加行级锁

MySQL8行级锁版本:8.0.34基本概念...

mysql使用小技巧_mysql使用入门

1、MySQL中有许多很实用的函数,好好利用它们可以省去很多时间:group_concat()将取到的值用逗号连接,可以这么用:selectgroup_concat(distinctid)fr...

MySQL/MariaDB中如何支持全部的Unicode?

永远不要在MySQL中使用utf8,并且始终使用utf8mb4。utf8mb4介绍MySQL/MariaDB中,utf8字符集并不是对Unicode的真正实现,即不是真正的UTF-8编码,因...

聊聊 MySQL Server 可执行注释,你懂了吗?

前言MySQLServer当前支持如下3种注释风格:...

MySQL系列-源码编译安装(v5.7.34)

一、系统环境要求...

MySQL的锁就锁住我啦!与腾讯大佬的技术交谈,是我小看它了

对酒当歌,人生几何!朝朝暮暮,唯有己脱。苦苦寻觅找工作之间,殊不知今日之事乃我心之痛,难道是我不配拥有工作嘛。自面试后他所谓的等待都过去一段时日,可惜在下京东上的小金库都要见低啦。每每想到不由心中一...

MySQL字符问题_mysql中字符串的位置

中文写入乱码问题:我输入的中文编码是urf8的,建的库是urf8的,但是插入mysql总是乱码,一堆"???????????????????????"我用的是ibatis,终于找到原因了,我是这么解决...

深圳尚学堂:mysql基本sql语句大全(三)

数据开发-经典1.按姓氏笔画排序:Select*FromTableNameOrderByCustomerNameCollateChinese_PRC_Stroke_ci_as//从少...

MySQL进行行级锁的?一会next-key锁,一会间隙锁,一会记录锁?

大家好,是不是很多人都对MySQL加行级锁的规则搞的迷迷糊糊,一会是next-key锁,一会是间隙锁,一会又是记录锁。坦白说,确实还挺复杂的,但是好在我找点了点规律,也知道如何如何用命令分析加...

一文讲清怎么利用Python Django实现Excel数据表的导入导出功能

摘要:Python作为一门简单易学且功能强大的编程语言,广受程序员、数据分析师和AI工程师的青睐。本文系统讲解了如何使用Python的Django框架结合openpyxl库实现Excel...

用DataX实现两个MySQL实例间的数据同步

DataXDataX使用Java实现。如果可以实现数据库实例之间准实时的...

MySQL数据库知识_mysql数据库基础知识

MySQL是一种关系型数据库管理系统;那废话不多说,直接上自己以前学习整理文档:查看数据库命令:(1).查看存储过程状态:showprocedurestatus;(2).显示系统变量:show...

如何为MySQL中的JSON字段设置索引

背景MySQL在2015年中发布的5.7.8版本中首次引入了JSON数据类型。自此,它成了一种逃离严格列定义的方式,可以存储各种形状和大小的JSON文档,例如审计日志、配置信息、第三方数据包、用户自定...

取消回复欢迎 发表评论: