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

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

ztj100 2025-03-19 18:44 13 浏览 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 属地北京

相关推荐

Java对象序列化与反序列化的那些事

Java对象序列化与反序列化的那些事在Java的世界里,对象序列化和反序列化就像一对孪生兄弟,它们共同构成了Java对象存储和传输的基础。如果你曾经尝试将对象保存到文件中,或者在网络中传输对象,那么你...

集合或数组转成String字符串(集合怎么转换成字符串)

1.将集合转成String字符串Strings="";for(inti=0;i<numList.size;i++){if(s==""){s=numL...

java学习分享:Java截取(提取)子字符串(substring())

在String中提供了两个截取字符串的方法,一个是从指定位置截取到字符串结尾,另一个是截取指定范围的内容。下面对这两种方法分别进行介绍。1.substring(intbeginIndex)形...

deepseek提示词:sql转c#代码示例。

SELECTRIGHT('0000'+CAST(DATEDIFF(DAY,'2024-01-01',GETDATE())ASVARCHAR(4)),4)...

Java 21 新特性的实践,确实很丝滑!

1虚拟线程创建虚拟线程...

为什么Java中的String是不可变的(Immutable)

在Java中,String类型是用于表示字符串的类,而字符串则是字符序列,是Java编程中最常用的数据类型之一。String类是不可变的,这意味着一旦创建,字符串的值就不能改变,下面我们就来介绍一下为...

Java中读取File文件内容转为String类型

@Java讲坛杨工开发中常常会碰到读取磁盘上的配置文件等内容,然后获取文件内容转字符串String类型,那么就需要编写一个API来实现这样的功能。首先准备一个测试需要的文件test.xml...

从Pandas快速切换到Polars :数据的ETL和查询

对于我们日常的数据清理、预处理和分析方面的大多数任务,Pandas已经绰绰有余。但是当数据量变得非常大时,它的性能开始下降。我们以前的两篇文章来测试Pandas1.5.3、polar和Pandas...

Pandas高手养成记:10个鲜为人知的高效数据处理技巧

Pandas是Python中非常强大的数据分析库,提供了高效的数据结构和数据处理工具。以下是一些鲜为人知但极其有用的Pandas数据处理技巧,可以帮助你提高工作效率:使用.eval()执行行...

灵活筛选数据,pandas无需指定行列的筛选方法,步骤详解

pandas库可轻松地筛选出符合特定条件的数据,无需指定筛选的行和列。通过灵活运用pandas的筛选功能,我们能够高效、准确地获取到感兴趣的数据,本文将介绍以下几种方法,在不指定行列的情况下使用pan...

【Pandas】(4)基本操作(pandas的基本操作)

选择数据获取列单列获取要获取DataFrame的单个列,你可以使用列名以两种不同的方式:...

「Python数据分析」Pandas基础,用iloc函数按行列位置选择数据

前面我们学过,使用loc函数,通过数据标签,也就是行标签和列标签来选择数据。行和列的标签,是在数据获取,或者是生成的时候,就已经定义好的。行数据标签,也就是唯一标识数据,不重复的一列,相当于数据库中的...

Python数据的选取和处理(python数据提取方法)

importpandasaspdimportnumpyasnpdata=pd.DataFrame(np.arange(1,10).reshape(3,3),index=['...

天秀!一张图就能彻底搞定Pandas(10分钟搞定pandas)

作者:刘早起公众号:早起Python大家好,在三月初,我曾给大家分享过一份Matplotlib绘图小抄,详见收下这份来自GitHub的神器,一图搞定Matplotlib!昨天在面向GitHub编程时,...

Python学不会来打我(92)python代码调试知识总结(五)属性问题

Attributeerror是属性问题,这个问题的报错也经常会出现,今天我们就分享一下:Python中引发AttributeError的常见原因及对应解决方案的详细分析。...

取消回复欢迎 发表评论: