### Start Local Backend Service Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.en.md These commands guide you through setting up and running the FastAPI backend locally. It includes installing dependencies, starting the development server, and managing database migrations. ```sh # Enter the backend project directory cd backend # Install dependencies pip3 install -r requirements.txt # Start the backend service python3 main.py run or python3 main.py run --env=dev # Generate migration files python3 main.py revision "Initial migration" --env=dev (default is dev if not specified) # Apply migrations python3 main.py upgrade --env=dev (default is dev if not specified) ``` -------------------------------- ### Start Backend Service (Python) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.md Instructions for setting up and running the FastAPI backend. This includes installing dependencies, starting the development server, and managing database migrations. ```python # 进入后端工程目录 cd backend # 安装依赖 pip3 install -r requirements.txt # 启动后端服务 python3 main.py run # 或 python3 main.py run--env=dev # 生成迁移文件 python3 main.py revision "初始化迁移" --env=dev(不加默认为dev) # 应用迁移 python3 main.py upgrade --env=dev(不加默认为dev) ``` -------------------------------- ### Project Setup and Development Commands (Bash) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Provides essential bash commands for setting up and running the FastAPI Vue3 Admin project. Includes commands for installing dependencies, starting the development server, building for production, and running various utility tasks like linting and formatting. ```bash # 进入项目目录 cd frontend # 安装依赖(推荐使用 pnpm) pnpm install # 启动开发服务器 pnpm run dev # 构建生产版本 pnpm run build # 预览构建结果 pnpm run preview # 代码检查 pnpm run lint # 类型检查 pnpm run type-check # 格式化代码 pnpm run lint:format # 清理缓存 pnpm run clean:cache ``` -------------------------------- ### Local H5 Mini Program Development Setup Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.md This section details the steps to set up and run the H5 mini-program frontend locally. It includes installing dependencies, starting the development server, and building for H5 deployment. ```sh # Enter the frontend project directory cd fastapp # Install dependencies pnpm install # Start the frontend service pnpm run dev:h5 # Build frontend, generate `frontend/dist/build/h5` directory pnpm run build:h5 ``` -------------------------------- ### Quick Start Deployment Script Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/devops/README.md This section provides commands to execute the deployment script, access the running application, and manage Docker resources. It includes steps for granting execute permissions, running the script, accessing the web interface and API documentation, logging in, and performing Docker operations like viewing images/containers, stopping services, and removing resources. Ensure the script `start.sh` is accessible and executable. ```sh # 复制脚本 `fastapi_vue3_amdin/start.sh` 脚本文件到服务器, 并赋予执行权限 chmod +x start.sh # 执行脚本 ./start.sh # 访问地址 # 前端访问: `http://公网地址:80`, # 接口访问: `http://公网地址:8001/api/v1/docs`, # 登录 `admin/123456` 或 `demo/123456` # 查看镜像: docsker images -a # 查看容器: docsker compose ps # 查看日志 docker logs -f <容器名> # 服务停止 docsker compose down # 删除镜像 docker rmi <镜像名> # 删除容器 docker rm <容器名> ``` -------------------------------- ### Start Local Frontend Service Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.en.md Instructions for running the Vue3 frontend locally. This involves installing project dependencies using pnpm, starting the development server, and building the project for production. ```sh # Enter the frontend project directory cd frontend # Install dependencies pnpm install # Start the frontend service pnpm run dev # Build the frontend and generate the `frontend/dist` directory pnpm run build ``` -------------------------------- ### Local Project Official Website Development Setup Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.md This section outlines the process for setting up and running the project's official website locally. It covers dependency installation, running the development server for documentation, and building the documentation project. ```sh # Enter the frontend project directory cd fastdocs # Install dependencies pnpm install # Run the documentation project pnpm run docs:dev # Build the documentation project, generate `fastdocs/dist` directory pnpm run docs:build ``` -------------------------------- ### Run Development Server (Bash) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/backend/README.md Commands to start the FastAPI application for development and production environments, including an example using uvicorn directly. ```bash # 开发环境启动 python3 main.py run --env=dev # 生产环境启动 python3 main.py run --env=prod # 或使用 uvicorn 直接启动 uvicorn main:app --host 0.0.0.0 --port 8000 --reload ``` -------------------------------- ### Start Frontend Service (Node.js/pnpm) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.md Steps to install frontend dependencies and start the Vue3 development server using pnpm. This is for running the frontend of the FastAPI-Vue3-Admin project locally. ```shell # 进入前端工程目录 cd frontend # 安装依赖 pnpm install # 启动前端服务 pnpm run dev ``` -------------------------------- ### Start Local Project Website Service Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.en.md Commands to run the project's documentation website locally. It utilizes pnpm for dependency installation and offers commands for both development and building the documentation site. ```sh # Enter the fastdocs project directory cd fastdocs # Install dependencies pnpm install # Run the documentation project pnpm run docs:dev # Build the documentation project and generate the `fastdocs/dist` directory pnpm run docs:build ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/backend/README.md Command to install project dependencies using pip, typically run after cloning the repository and activating a virtual environment. ```bash # 克隆项目 git clone cd fastapi_vue3_admin/backend # 创建虚拟环境(推荐) python3 -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate # 安装依赖 pip3 install -r requirements.txt ``` -------------------------------- ### TypeScript - Pinia Store for Example Data Management Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Implements a Pinia store module for managing 'example' data. It includes state variables (`exampleList`, `loading`), computed properties (`activeExamples`), and actions for fetching, adding, updating, and removing examples. It integrates with the API module for data operations. ```typescript // src/store/modules/example.store.ts import { defineStore } from 'pinia' import { ref, computed } from 'vue' import type { ExampleData } from '@/api/example' export const useExampleStore = defineStore('example', () => { // 状态 const exampleList = ref([]) const loading = ref(false) // 计算属性 const activeExamples = computed(() => exampleList.value.filter(item => item.status === 'active') ) // 动作 const fetchExampleList = async () => { loading.value = true try { const { data } = await getExampleList() exampleList.value = data } catch (error) { console.error('获取示例列表失败:', error) } finally { loading.value = false } } const addExample = async (data: Omit) => { await createExample(data) await fetchExampleList() } const updateExample = async (id: number, data: Partial) => { await updateExample(id, data) // Note: This appears to be a recursive call to itself, should likely be `api.updateExample` await fetchExampleList() } const removeExample = async (id: number) => { await deleteExample(id) await fetchExampleList() } return { // 状态 exampleList, loading, // 计算属性 activeExamples, // 动作 fetchExampleList, addExample, updateExample, removeExample } }) ``` -------------------------------- ### FastAPI Backend Setup and Commands (Python) Source: https://context7.com/1014taotao/fastapi_vue3_admin/llms.txt Main entry point for the FastAPI backend application. It includes functions to create the FastAPI app, run the Uvicorn server, and manage Alembic database migrations. This script defines CLI commands for development and deployment. ```python import os import uvicorn import typer from fastapi import FastAPI from alembic import command from alembic.config import Config shell_app = typer.Typer() alembic_cfg = Config("alembic.ini") def create_app() -> FastAPI: """Create and configure FastAPI application""" from app.config.setting import settings from app.plugin.init_app import ( register_middlewares, register_exceptions, register_routers, register_files, reset_api_docs, lifespan ) # Create FastAPI instance app = FastAPI(**settings.FASTAPI_CONFIG, lifespan=lifespan) # Register components in order register_exceptions(app) # Exception handlers register_middlewares(app) # CORS, logging, etc. register_routers(app) # API endpoints register_files(app) # Static files reset_api_docs(app) # Swagger/ReDoc return app @shell_app.command() def run(env: str = typer.Option("dev", "--env", help="Environment (dev, prod)")): """Start uvicorn server""" typer.echo("Starting application...") os.environ["ENVIRONMENT"] = env from app.config.setting import settings uvicorn.run( app='main:create_app', **settings.UVICORN_CONFIG ) @shell_app.command() def revision(message: str, env: str = typer.Option("dev", "--env")): """Generate Alembic migration script""" os.environ["ENVIRONMENT"] = env command.revision(alembic_cfg, message=message, autogenerate=True) typer.echo(f"Migration created: {message}") @shell_app.command() def upgrade(env: str = typer.Option("dev", "--env")): """Apply latest Alembic migrations""" os.environ["ENVIRONMENT"] = env command.upgrade(alembic_cfg, "head") typer.echo("All migrations applied.") if __name__ == '__main__': # Commands: # python3 main.py run --env=dev # python3 main.py revision "Initial migration" --env=dev # python3 main.py upgrade --env=dev shell_app() ``` -------------------------------- ### Menu Type Configuration Examples (JSON) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md JSON examples illustrating different menu types (CATALOG, MENU, BUTTON, EXTLINK) used within the admin system. Each type has specific configuration properties relevant to its function, such as `children` for catalogs or `route_path` for external links. ```json { "type": "CATALOG", "route_path": "/system", "route_name": "System", "component_path": null, "children": [...] // 子菜单数组 } ``` ```json { "type": "MENU", "route_path": "/system/user", "route_name": "SystemUser", "component_path": "system/user/index", "keep_alive": true } ``` ```json { "type": "BUTTON", "name": "用户新增", "route_path": null, "route_name": null, "component_path": null } ``` ```json { "type": "EXTLINK", "route_path": "https://example.com", "route_name": "ExternalLink" } ``` -------------------------------- ### Deployment Configuration Files Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/devops/README.md This lists the key configuration files for backend, frontend, and Docker deployment. These files are crucial for troubleshooting and customizing the deployment environment. Ensure correct paths are used when modifying these files. ```text - 后端配置文件 `fastapi_vue3_amdin/backend/env/.env.prod.py` - 前端配置文件 `fastapi_vue3_amdin/frontend/vite.config.ts` 和 `fastapi_vue3_amdin/frontend/.env.production` - 部署文件 `fastapi_vue3_amdin/docker-compose.yaml` 和 `fastapi_vue3_amdin/devops/devops/nginx/nginx.conf` ``` -------------------------------- ### Dockerfile for FastAPI Application Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md A Dockerfile to containerize the FastAPI application. It sets up a Python 3.10 environment, installs dependencies from requirements.txt, copies the application code, and defines the command to run the application using uvicorn. ```dockerfile # Dockerfile FROM python:3.10-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] ``` -------------------------------- ### Development Environment Configuration (.env.dev.py) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Defines environment variables for the development setup, including application settings, server host and port, database connection URL, Redis URL, and JWT configuration. This file is crucial for running the application in a development context. ```python # 应用配置 APP_ENV = "development" DEBUG = True # 服务器配置 HOST = "127.0.0.1" PORT = 8000 # 数据库配置 DATABASE_URL = "mysql+pymysql://root:password@localhost:3306/fastapi_admin" # Redis配置 REDIS_URL = "redis://localhost:6379/0" # JWT配置 JWT_SECRET_KEY = "your-secret-key" JWT_ALGORITHM = "HS256" JWT_ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 其他配置 ``` -------------------------------- ### Project Directory Structure Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/devops/README.md This shows the hierarchical organization of the project's DevOps-related directories, including backend, database, and web server configurations. ```sh fastapi_project/devops/ ├─ backend # 后端部署目录 ├─ mysql # mysql部署目录 ├─ nginx # nginx部署目录 ├─ redis # redis部署目录 └─ README.md # 项目说明文档 ``` -------------------------------- ### TypeScript - API Module for Example Data Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Defines API request functions for managing 'example' data. It includes functions for fetching a list, creating, updating, and deleting examples, utilizing a generic `request` utility. It also defines an interface `ExampleData` for the data structure. ```typescript // src/api/example.ts import request from '@/utils/request' export interface ExampleData { id: number name: string status: string } export const getExampleList = (params?: any) => { return request.get('/example/list', { params }) } export const createExample = (data: Omit) => { return request.post('/example', data) } export const updateExample = (id: number, data: Partial) => { return request.put(`/example/${id}`, data) } export const deleteExample = (id: number) => { return request.delete(`/example/${id}`) } ``` -------------------------------- ### TypeScript - Utility Functions for Example Data Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Provides utility functions for formatting and validating 'example' data. `formatExampleData` transforms raw data into the `ExampleData` interface, providing default values if needed. `validateExampleData` checks for required fields and returns an array of error messages. ```typescript // src/utils/example.ts /** * 格式化示例数据 */ export const formatExampleData = (data: any): ExampleData => { return { id: data.id, name: data.name || '', status: data.status || 'inactive' } } /** * 验证示例数据 */ export const validateExampleData = (data: Partial): string[] => { const errors: string[] = [] if (!data.name?.trim()) { errors.push('名称不能为空') } if (!data.status) { errors.push('状态不能为空') } return errors } ``` -------------------------------- ### Start Local App H5 Service Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.en.md This section details how to run the H5 version of the application locally. It uses pnpm for dependency management and provides commands for both development and building the H5 application. ```sh # Enter the fastapp project directory cd fastapp # Install dependencies pnpm install # Start the fastapp service pnpm run dev:h5 # Build the fastapp and generate the `fastapp/dist/build/h5` directory pnpm run build:h5 ``` -------------------------------- ### User Creation API Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Allows for the creation of new users in the system. Requires user details in the request body. ```APIDOC ## POST /api/v1/users/ ### Description Creates a new user. ### Method POST ### Endpoint /api/v1/users/ ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "johndoe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (200) - **code** (integer) - The status code, typically 200. - **data** (object) - The created user object. - **message** (string) - A success message. #### Response Example ```json { "code": 200, "data": { "id": 1, "username": "johndoe", "email": "johndoe@example.com" }, "message": "用户创建成功" } ``` ``` -------------------------------- ### Docker Compose for Multi-Container Deployment (YAML) Source: https://context7.com/1014taotao/fastapi_vue3_admin/llms.txt Defines the Docker Compose setup for deploying the FastAPI application with MySQL, Redis, and Nginx. It specifies services, images, environment variables, volumes, ports, and network configurations for a cohesive multi-container environment. ```yaml # File: docker-compose.yaml services: # MySQL database service mysql: container_name: mysql image: mysql:8.0 restart: always environment: TZ: "Asia/Shanghai" MYSQL_ROOT_PASSWORD: "FastApi123abc" MYSQL_DATABASE: "fastapiadmin" ports: - "3306:3306" volumes: - ./devops/mysql/data:/var/lib/mysql - ./devops/mysql/conf:/etc/mysql/conf.d - ./devops/mysql/logs:/var/log/mysql networks: - app_network # Redis cache service redis: container_name: redis image: redis:6 restart: always environment: TZ: "Asia/Shanghai" ports: - "6379:6379" volumes: - ./devops/redis/conf/redis.conf:/etc/redis/redis.conf - ./devops/redis/data:/data - ./devops/redis/logs:/var/log/redis command: redis-server /etc/redis/redis.conf networks: - app_network # FastAPI backend service backend: container_name: backend build: context: ./. dockerfile: ./devops/backend/Dockerfile image: backend:latest restart: always environment: TZ: "Asia/Shanghai" DATABASE_URL: "mysql+aiomysql://root:FastApi123abc@mysql:3306/fastapiadmin" REDIS_URL: "redis://redis:6379/0" ports: - "8001:8001" volumes: - ./backend:/home depends_on: - mysql - redis networks: - app_network # Nginx frontend service nginx: container_name: nginx image: nginx:latest restart: always environment: TZ: "Asia/Shanghai" ports: - "80:80" - "443:443" volumes: - ./devops/nginx/nginx.conf:/etc/nginx/nginx.conf - ./frontend/dist:/usr/share/nginx/html/frontend - ./fastapp/dist/build/h5:/usr/share/nginx/html/fastapp - ./fastdocs/dist:/usr/share/nginx/html/fastdocs depends_on: - backend networks: - app_network networks: app_network: driver: bridge # Deployment commands: # chmod +x deploy.sh # ./deploy.sh # docker compose ps # View containers # docker logs -f backend # View backend logs # docker compose down # Stop all services ``` -------------------------------- ### Production Environment Configuration (.env.prod.py) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Specifies environment variables for the production deployment. It includes settings for application mode, server host and port, database connection, Redis connection, and JWT configuration, optimized for a production environment. ```python # 应用配置 APP_ENV = "production" DEBUG = False # 服务器配置 HOST = "0.0.0.0" PORT = 8000 # 数据库配置 DATABASE_URL = "mysql+pymysql://user:password@db:3306/fastapi_admin" # Redis配置 REDIS_URL = "redis://redis:6379/0" # JWT配置 JWT_SECRET_KEY = "your-production-secret-key" JWT_ALGORITHM = "HS256" JWT_ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 其他配置 ``` -------------------------------- ### Get User by ID API Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Retrieves detailed information about a specific user based on their unique identifier. ```APIDOC ## GET /api/v1/users/{user_id} ### Description Retrieves information for a specific user by their ID. ### Method GET ### Endpoint /api/v1/users/{user_id} ### Parameters #### Path Parameters - **user_id** (integer) - Required - The unique identifier of the user. ### Request Example ```json { "example": "No request body needed for GET request" } ``` ### Response #### Success Response (200) - **code** (integer) - The status code, typically 200. - **data** (object) - The user object. - **message** (string) - A success message. #### Response Example ```json { "code": 200, "data": { "id": 1, "username": "johndoe", "email": "johndoe@example.com" }, "message": "获取用户信息成功" } ``` #### Error Response (404) - **detail** (string) - Error message indicating the user was not found. ``` -------------------------------- ### Database Initialization (Bash) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/backend/README.md Commands to manage database migrations and initialize data using the Alembic tool via the main Python script. ```bash # 生成迁移文件(仅首次或模型变更时) python3 main.py revision "初始化迁移" --env=dev # 应用数据库迁移 python3 main.py upgrade --env=dev # 初始化数据(可选,系统会自动初始化) python3 main.py init-data --env=dev ``` -------------------------------- ### Scheduled Task for Token Cleanup (Python) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Configures and initializes an asynchronous scheduler (APScheduler) to run background tasks. Includes a sample scheduled job to clean up expired tokens at regular intervals. The scheduler is started only when the application environment is not 'testing'. ```python from apscheduler.schedulers.asyncio import AsyncIOScheduler from app.core.config import settings scheduler = AsyncIOScheduler() @scheduler.scheduled_job("interval", minutes=30) async def clean_expired_tokens(): """清理过期令牌""" # 实现清理逻辑 pass def init_scheduler(): """初始化调度器""" if settings.APP_ENV != "testing": scheduler.start() ``` -------------------------------- ### Get User API Endpoint (Python) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Defines the API endpoint to retrieve user information by their ID using FastAPI. It employs dependency injection for authentication (`get_current_active_user`) and calls the UserService to fetch user data. Returns a 404 error if the user is not found. ```python from fastapi import APIRouter, Depends, HTTPException from app.api.v1.services.user_service import UserService from app.api.v1.schemas.user_schema import UserCreate, UserUpdate from app.deps import get_current_active_user router = APIRouter() @router.get("/{user_id}") async def get_user(user_id: int, current_user = Depends(get_current_active_user)): """获取用户信息""" user = await UserService.get_user_by_id(user_id) if not user: raise HTTPException(status_code=404, detail="用户不存在") return {"code": 200, "data": user, "message": "获取用户信息成功"} ``` -------------------------------- ### API User Authentication Dependencies (Python) Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/backend.md Provides functions to get the current user and the current active user from JWT tokens. It handles token validation, user retrieval from the database, and checks user activity status. Relies on JOSE for JWT decoding and a UserService for user data access. ```python from fastapi import Depends, HTTPException, status from jose import jwt, JWTError from app.core.config import settings from app.core.security import ALGORITHM from app.services.user_service import UserService # Assuming UserService is defined elsewhere async def get_current_user(token: str = Depends(oauth2_scheme)): """获取当前用户""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM]) user_id: str = payload.get("sub") if user_id is None: raise credentials_exception except JWTError: raise credentials_exception user = await UserService.get_user_by_id(int(user_id)) if user is None: raise credentials_exception return user async def get_current_active_user(current_user = Depends(get_current_user)): """获取当前活跃用户""" if not current_user.is_active: raise HTTPException(status_code=400, detail="Inactive user") return current_user ``` -------------------------------- ### Project Structure Overview Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/backend/README.md Illustrates the directory layout of the FastAPI Vue3 Admin backend project, highlighting key modules like API, common components, configuration, core functionalities, and utilities. ```txt fastapi_vue3_admin/backend/ ├── 📁 app/ # 项目核心代码 │ ├── 💾 alembic/ # 数据库迁移管理 │ ├── 🌐 api/ # API 接口模块 │ │ └── v1/ # API v1 版本 │ │ ├── module_system/ # 系统管理模块 │ │ ├── module_monitor/ # 系统监控模块 │ │ ├── module_ai/ # AI 功能模块 │ │ └── module_*/ # 其他业务模块 │ ├── 📄 common/ # 公共组件(常量、枚举、响应封装) │ ├── ⚙️ config/ # 项目配置文件 │ ├── 💖 core/ # 核心模块(数据库、中间件、安全) │ ├── ⏰ module_task/ # 定时任务模块 │ ├── 🔌 plugin/ # 插件模块 │ ├── 📜 scripts/ # 初始化脚本和数据 │ └── 🛠️ utils/ # 工具类(验证码、文件上传等) ├── 🌍 env/ # 环境配置文件 ├── 📄 logs/ # 日志输出目录 ├── 📊 sql/ # SQL 初始化脚本 ├── 📷 static/ # 静态资源文件 ├── 🚀 main.py # 项目启动入口 ├── 📄 alembic.ini # Alembic 迁移配置 ├── 📎 requirements.txt # Python 依赖包 └── 📝 README.md # 项目说明文档 ``` -------------------------------- ### 克隆 FastAPI Vue3 Admin 项目 Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/quickstart/start.md 使用 Git 克隆 FastAPI Vue3 Admin 项目的源代码到本地。支持 Gitee 和 GitHub 两个仓库地址。 ```sh # 克隆代码到本地 git clone https://gitee.com/tao__tao/fastapi_vue3_admin.git 或 git clone https://github.com/1014TaoTao/fastapi_vue3_admin.git ``` -------------------------------- ### Bash Commands for Building Production Versions Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Lists bash commands for building the project for production and specific environments (development, testing). These commands are used in the deployment process. ```bash # 构建生产版本 pnpm run build # 构建特定环境 pnpm run build:pro # 生产环境 pnpm run build:dev # 开发环境 pnpm run build:test # 测试环境 ``` -------------------------------- ### Docker Deployment Script Execution Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.md These commands demonstrate how to deploy the application using Docker. It involves copying a deployment script, making it executable, running the script, and managing Docker containers and images. It also points to configuration file locations. ```sh # Copy the script `fastapi_vue3_amdin/deploy.sh` to the server and grant execution permissions chmod +x deploy.sh # Execute the script ./deploy.sh # View images: docker images -a # View containers: docker compose ps # View logs docker logs -f # Stop service docker compose down # Delete image docker rmi # Delete container docker rm # Backend configuration file directory fastapi_vue3_amdin/backend/env/.env.prod.py # Frontend configuration file directory fastapi_vue3_amdin/frontend/vite.config.ts and fastapi_vue3_amdin/frontend/.env.production # Deployment file directory fastapi_vue3_amdin/docker-compose.yaml and fastapi_vue3_amdin/devops/devops/nginx/nginx.conf ``` -------------------------------- ### 本地启动项目官网文档服务 Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/quickstart/start.md 在本地启动项目官网文档服务。包括安装依赖、运行开发服务器以及构建生产版本。推荐使用 pnpm 进行包管理。 ```sh # 进入前端工程目录 cd fastdocs # 安装依赖 pnpm install # 运行文档工程 pnpm run docs:dev # 构建文档工程, 生成 `fastdocs/dist` 目录 pnpm run docs:build ``` -------------------------------- ### TypeScript Constants and Enums for Example Module Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Defines constants for example status, their corresponding text representations, and default page size. These values centralize common configurations and improve readability. ```typescript // src/constants/example.ts export const EXAMPLE_STATUS = { ACTIVE: 'active', INACTIVE: 'inactive' } as const export const EXAMPLE_STATUS_TEXT = { [EXAMPLE_STATUS.ACTIVE]: '启用', [EXAMPLE_STATUS.INACTIVE]: '禁用' } as const export const EXAMPLE_PAGE_SIZE = 20 ``` -------------------------------- ### TypeScript Type Definitions for Example Module Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/development/frontend.md Defines TypeScript interfaces for example data, forms, and query parameters. These types help ensure data consistency and improve code maintainability within the application. ```typescript // src/types/example.d.ts export interface ExampleData { id: number name: string status: 'active' | 'inactive' createdAt: string updatedAt: string } export interface ExampleForm { name: string status: 'active' | 'inactive' } export interface ExampleQuery { page?: number size?: number name?: string status?: 'active' | 'inactive' } ``` -------------------------------- ### Docker Deployment Script Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.en.md This section covers deploying the project using Docker. It includes steps to copy and execute a deployment script, manage Docker images and containers, and view logs. Configuration file paths are also provided. ```sh # Copy the script `fastapi_vue3_admin/deploy.sh` to the server and grant execution permissions chmod +x deploy.sh # Execute the script ./deploy.sh # View images: docker images -a # View containers: docker compose ps # View logs docker logs -f # Stop the service docker compose down # Delete an image docker rmi # Delete a container docker rm # Backend configuration file directory fastapi_vue3_admin/backend/env/.env.prod.py # Frontend configuration file directory fastapi_vue3_admin/frontend/vite.config.ts and fastapi_vue3_admin/frontend/.env.production ``` -------------------------------- ### 使用 Docker 部署 FastAPI Vue3 Admin Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/fastdocs/src/quickstart/start.md 使用 Docker 部署 FastAPI Vue3 Admin 项目。包括复制启动脚本、赋予执行权限、执行脚本、查看镜像和容器、查看日志、停止服务、删除镜像和容器等操作。 ```sh # 复制脚本 `fastapi_vue3_admin/start.sh` 脚本文件到服务器, 并赋予执行权限 chmod +x start.sh # 执行脚本 ./start.sh # 查看镜像: docker images -a # 查看容器: docker compose ps # 查看日志 docker logs -f <容器名> # 服务停止 docker compose down # 删除镜像 docker rmi <镜像名> # 删除容器 docker rm <容器名> ``` -------------------------------- ### GET /api/v1/system/user/list Source: https://context7.com/1014taotao/fastapi_vue3_admin/llms.txt Retrieves a list of users with support for pagination, filtering, and sorting. ```APIDOC ## GET /api/v1/system/user/list ### Description Retrieves a list of users with support for pagination, filtering, and sorting. ### Method GET ### Endpoint /api/v1/system/user/list ### Parameters #### Query Parameters - **page_no** (integer) - Optional - The page number for pagination (default is 1). - **page_size** (integer) - Optional - The number of items per page (default is 10). - **username** (string) - Optional - Filter users by username. - **status** (boolean) - Optional - Filter users by their status (true for active, false for inactive). - **search** (object) - Optional - An object for advanced filtering (structure depends on backend implementation). - **order_by** (array of objects) - Optional - An array of objects specifying sorting criteria (e.g., `[{"field": "username", "direction": "asc"}]`). #### Headers - **Authorization** (string) - Required - Bearer token for authentication ### Request Example ``` GET /api/v1/system/user/list?page_no=1&page_size=10&username=admin&status=true ``` ### Response #### Success Response (200) - **code** (integer) - Response status code. - **msg** (string) - Message indicating success. - **data** (object) - Contains the paginated list of users. - **total** (integer) - The total number of users matching the criteria. - **page_no** (integer) - The current page number. - **page_size** (integer) - The number of items per page. - **list** (array of objects) - An array of user objects. - **id** (integer) - The unique identifier for the user. - **username** (string) - The username of the user. - **name** (string) - The full name of the user. - **email** (string) - The email address of the user. - **dept_name** (string) - The name of the department the user belongs to. - **status** (boolean) - The status of the user account. #### Response Example ```json { "code": 200, "msg": "Query successful", "data": { "total": 100, "page_no": 1, "page_size": 10, "list": [ { "id": 1, "username": "admin", "name": "Administrator", "email": "admin@example.com", "dept_name": "Technology", "status": true } ] } } ``` ``` -------------------------------- ### Vue3 Code Generation Logic Example Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/frontend/src/views/gencode/webcode/README.md This snippet shows a conceptual example of code generation logic within the 'serializer.ts' utility file. It demonstrates how to take a component's configuration (schema and properties) and transform it into a Vue 3 component string. This function would be part of a larger serialization process to generate entire .vue files. ```typescript // Example structure within src/views/gencode/backcode/utils/serializer.ts import schemas from './schema'; interface ComponentInstance { id: string; tag: string; props: { [key: string]: any; }; children?: ComponentInstance[]; } function generateComponentCode(component: ComponentInstance): string { const schema = schemas[component.tag]; if (!schema) { return ``; } let propsString = ''; for (const prop in component.props) { if (Object.prototype.hasOwnProperty.call(component.props, prop)) { const value = component.props[prop]; const schemaProp = schema.properties[prop]; // Basic type handling, could be more sophisticated if (schemaProp.type === 'string' && typeof value === 'string') { propsString += ` ${prop}="${value}"`; } else if (typeof value === 'boolean' && value) { propsString += ` ${prop}`; } else if (typeof value !== 'undefined' && value !== null) { propsString += ` ${prop}=${JSON.stringify(value)}`; } } } let childrenCode = ''; if (component.children && component.children.length > 0) { childrenCode = component.children.map(child => generateComponentCode(child)).join('\n'); } return `<${component.tag}${propsString}>\n${childrenCode}\n`; } export function generateVueFileContent(rootComponent: ComponentInstance): string { const componentCode = generateComponentCode(rootComponent); return ` `; } ``` -------------------------------- ### FastAPI Application Factory Main Entry Point Source: https://context7.com/1014taotao/fastapi_vue3_admin/llms.txt This Python code outlines the main entry point for a FastAPI application, functioning as an application factory. It is responsible for creating the FastAPI instance, configuring middleware, registering routes, and managing application lifecycle events. This structure promotes modularity and allows for customization during application setup. ```python from fastapi import FastAPI def create_app() -> FastAPI: """FastAPI application factory""" app = FastAPI( title="My FastAPI App", description="A sample FastAPI application.", version="1.0.0" ) # Add middleware here # e.g., app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],) # Include routers here # e.g., app.include_router(user_router, prefix="/users") # e.g., app.include_router(item_router, prefix="/items") # Add event handlers for startup and shutdown @app.on_event("startup") async def startup_event(): print("Application startup...") # Initialize database connections, etc. @app.on_event("shutdown") async def shutdown_event(): print("Application shutdown...") # Close database connections, etc. @app.get("/") async def root(): return {"message": "Welcome to the API!"} return app app = create_app() # To run this application, you would typically use an ASGI server like uvicorn: # uvicorn main:app --reload ``` -------------------------------- ### GET /api/v1/system/auth/captcha/get Source: https://context7.com/1014taotao/fastapi_vue3_admin/llms.txt Generates and returns a CAPTCHA image for login security, with the CAPTCHA key and image data provided in the response. ```APIDOC ## GET /api/v1/system/auth/captcha/get ### Description Generates a CAPTCHA image and its corresponding key for user verification. ### Method GET ### Endpoint /api/v1/system/auth/captcha/get ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```bash curl -X GET "http://localhost:8001/api/v1/system/auth/captcha/get" ``` ### Response #### Success Response (200) - **captcha_key** (string) - A unique identifier for the generated CAPTCHA. - **captcha_image** (string) - The CAPTCHA image encoded in base64 format (e.g., data:image/png;base64,...). #### Response Example ```json { "code": 200, "msg": "Captcha generated successfully", "data": { "captcha_key": "captcha_1234567890", "captcha_image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." } } ``` ``` -------------------------------- ### Project Structure Overview Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/README.en.md This snippet outlines the directory structure of the fastapi_vue3_admin project. It categorizes the main components including backend, frontend, mobile, documentation, and deployment-related files. ```sh fastapi_vue3_admin ├─ backend # Backend project ├─ frontend # Frontend project ├─ fastapp # Mobile project ├─ fastdocs # Official Website project ├─ devops # Deployment project ├─ docker-compose.yaml # Deployment file ├─ start.sh # One-click deployment script ├─ LICENSE # License agreement |─ README.en.md # English documentation └─ README.md # Chinese documentation ``` -------------------------------- ### GET /api/v1/system/user/current/info Source: https://context7.com/1014taotao/fastapi_vue3_admin/llms.txt Retrieves the currently authenticated user's profile information, including their roles, permissions, and the menu tree they have access to. ```APIDOC ## GET /api/v1/system/user/current/info ### Description Retrieves the currently authenticated user's profile information, including their roles, permissions, and the menu tree they have access to. ### Method GET ### Endpoint /api/v1/system/user/current/info ### Parameters None ### Request Example ```bash curl -X GET "http://localhost:8001/api/v1/system/user/current/info" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **code** (integer) - Status code, typically 200 for success. - **msg** (string) - A message indicating success. - **data** (object) - Contains the user's profile information. - **id** (integer) - User's unique identifier. - **username** (string) - User's username. - **name** (string) - User's full name. - **email** (string) - User's email address. - **mobile** (string) - User's mobile number. - **avatar** (string) - URL to the user's avatar. - **dept_name** (string) - The name of the department the user belongs to. - **status** (boolean) - The status of the user account (active/inactive). - **menus** (array) - A tree structure representing the menus the user has access to. #### Response Example (Success) ```json { "code": 200, "msg": "Success", "data": { "id": 1, "username": "admin", "name": "Administrator", "email": "admin@example.com", "mobile": "13800138000", "avatar": "http://example.com/avatar.jpg", "dept_name": "Technology Department", "status": true, "menus": [ { "id": 1, "name": "System", "path": "/system", "children": [ {"id": 2, "name": "User Management", "path": "/system/user"} ] } ] } } ``` ``` -------------------------------- ### Contribution Workflow - Git Commands Source: https://github.com/1014taotao/fastapi_vue3_admin/blob/master/backend/README.md Outlines the standard Git workflow for contributing to the project, including forking the repository, creating feature branches, committing changes, pushing to a remote branch, and initiating a pull request. ```bash 1. Fork 项目 2. 创建特性分支 (`git checkout -b feature/amazing-feature`) 3. 提交更改 (`git commit -m 'Add some amazing feature'`) 4. 推送到分支 (`git push origin feature/amazing-feature`) 5. 发起 Pull Request ```