网站首页 > 基础教程 正文
通常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 文件
<template>
<div>
<!-- 添加数据的表单部分 -->
<form @submit.prevent="addItem" class="large-form">
<textarea v-model="newItem.http_request" placeholder="Request" required class="form-textarea"></textarea>
<textarea v-model="newItem.http_response" placeholder="Response" required class="form-textarea"></textarea>
<button type="submit">Add</button>
</form>
<!-- 表格 -->
<table>
<!-- 表头 -->
<thead>
<tr>
<th>ID</th>
<th>Request</th>
<th>Response</th>
<th>Attack Result</th>
<th>Status</th>
</tr>
</thead>
<!-- 表格内容 -->
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.http_request }}</td>
<td>{{ item.http_response }}</td>
<td>{{ item.attack_result }}</td>
<!-- 按钮列 -->
<td>
<button @click="markAsSuccessful(item.id)">Successful</button>
<button @click="markAsFailed(item.id)">Failed</button>
<button @click="deleteItem(item.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<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>
<style scoped>
table {
width: 50%; /* 设置表格宽度 */
margin: auto; /* 使用auto来居中 */
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: center;
}
td {
text-align: center;
}
/* 添加大表单样式 */
.large-form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
height: 150px; /* 根据需要调整高度 */
}
/* 设置多行文本框样式 */
.form-textarea {
height: 80px; /* 根据需要调整高度 */
width: 50%;
margin-bottom: 10px;
}
</style>
(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:22?IP 属地北京
- 上一篇: SpringBoot 接口加解密全过程详解
- 下一篇: 通过构建背景图学习CSS径向渐变
猜你喜欢
- 2025-01-16 SpringBoot 接口加解密全过程详解
- 2025-01-16 el-table打印PDF预览,表头错位的解决方案
- 2025-01-16 前端必须掌握的知识,什么是盒子模型?
- 2025-01-16 基于Chrome内置AI的Web应用开发
- 2025-01-16 带有BME280的ESP32 Web服务器
- 2025-01-16 实时数据显示--SignalR实例演示
- 2025-01-16 原生js实现回复评论功能
- 2025-01-16 js事件机制详解
- 2025-01-16 桌面程序嵌套Web项目实践之WPF和Blazor混合应用开发
- 2025-01-16 用 Markdown Here 插件排版微信公共帐号文章
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)