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

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

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

相关推荐

30天学会Python编程:16. Python常用标准库使用教程

16.1collections模块16.1.1高级数据结构16.1.2示例...

强烈推荐!Python 这个宝藏库 re 正则匹配

Python的re模块(RegularExpression正则表达式)提供各种正则表达式的匹配操作。...

Python爬虫中正则表达式的用法,只讲如何应用,不讲原理

Python爬虫:正则的用法(非原理)。大家好,这节课给大家讲正则的实际用法,不讲原理,通俗易懂的讲如何用正则抓取内容。·导入re库,这里是需要从html这段字符串中提取出中间的那几个文字。实例一个对...

Python数据分析实战-正则提取文本的URL网址和邮箱(源码和效果)

实现功能:Python数据分析实战-利用正则表达式提取文本中的URL网址和邮箱...

python爬虫教程之爬取当当网 Top 500 本五星好评书籍

我们使用requests和re来写一个爬虫作为一个爱看书的你(说的跟真的似的)怎么能发现好书呢?所以我们爬取当当网的前500本好五星评书籍怎么样?ok接下来就是学习python的正确姿...

深入理解re模块:Python中的正则表达式神器解析

在Python中,"re"是一个强大的模块,用于处理正则表达式(regularexpressions)。正则表达式是一种强大的文本模式匹配工具,用于在字符串中查找、替换或提取特定模式...

如何使用正则表达式和 Python 匹配不以模式开头的字符串

需要在Python中使用正则表达式来匹配不以给定模式开头的字符串吗?如果是这样,你可以使用下面的语法来查找所有的字符串,除了那些不以https开始的字符串。r"^(?!https).*&...

先Mark后用!8分钟读懂 Python 性能优化

从本文总结了Python开发时,遇到的性能优化问题的定位和解决。概述:性能优化的原则——优化需要优化的部分。性能优化的一般步骤:首先,让你的程序跑起来结果一切正常。然后,运行这个结果正常的代码,看看它...

Python“三步”即可爬取,毋庸置疑

声明:本实例仅供学习,切忌遵守robots协议,请不要使用多线程等方式频繁访问网站。#第一步导入模块importreimportrequests#第二步获取你想爬取的网页地址,发送请求,获取网页内...

简单学Python——re库(正则表达式)2(split、findall、和sub)

1、split():分割字符串,返回列表语法:re.split('分隔符','目标字符串')例如:importrere.split(',','...

Lavazza拉瓦萨再度牵手上海大师赛

阅读此文前,麻烦您点击一下“关注”,方便您进行讨论和分享。Lavazza拉瓦萨再度牵手上海大师赛标题:2024上海大师赛:网球与咖啡的浪漫邂逅在2024年的上海劳力士大师赛上,拉瓦萨咖啡再次成为官...

ArkUI-X构建Android平台AAR及使用

本教程主要讲述如何利用ArkUI-XSDK完成AndroidAAR开发,实现基于ArkTS的声明式开发范式在android平台显示。包括:1.跨平台Library工程开发介绍...

Deepseek写歌详细教程(怎样用deepseek写歌功能)

以下为结合DeepSeek及相关工具实现AI写歌的详细教程,涵盖作词、作曲、演唱全流程:一、核心流程三步法1.AI生成歌词-打开DeepSeek(网页/APP/API),使用结构化提示词生成歌词:...

“AI说唱解说影视”走红,“零基础入行”靠谱吗?本报记者实测

“手里翻找冻鱼,精心的布局;老漠却不言语,脸上带笑意……”《狂飙》剧情被写成歌词,再配上“科目三”背景音乐的演唱,这段1分钟30秒的视频受到了无数网友的点赞。最近一段时间随着AI技术的发展,说唱解说影...

AI音乐制作神器揭秘!3款工具让你秒变高手

在音乐创作的领域里,每个人都有一颗想要成为大师的心。但是面对复杂的乐理知识和繁复的制作过程,许多人的热情被一点点消磨。...

取消回复欢迎 发表评论: