FastAPI启动报错:Import error: No module named 'routers' 求助
FastAPI 启动报错:Import error: No module named 'routers'
尝试基于自定义API提供商构建FastAPI项目,按官方文档操作,执行fastapi run命令时触发错误:ERROR Import error: No module named 'routers'。已确认routers目录和项目根目录都存在__init__.py文件,相关代码及项目结构如下:
项目文件结构

main.py 代码
import sys from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session #from core.config import settings import sys from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session sys.path.append('/routers/chat_order_router') # Append the directory from routers.chat_order_router import order_router app = FastAPI() app.include_router(order_router) @app.get("/") def read_root(): return {"Hello": "World"}
chat_order_router.py 代码
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import List from dependencies import get_db from schemas.chat_schema import ChatCreateSchema, ChatResponseSchema from models.chat import Chat import os from dotenv import load_dotenv from services.zus_backend_service import ZusBackendService # Ensure this is correctly imported import pytest from httpx import Response order_router = APIRouter( prefix="/chats_order", tags=["chats_order"], responses={404: {"description": "Not found"}}, ) load_dotenv() # Dependency def get_zus_service(): base_uri = os.getenv('ZUS_BE_URL') # Default value if not set client_name = os.getenv('ZUS_BE_NAME') client_secret = os.getenv('ZUS_BE_SECRET') if not base_uri or not client_name or not client_secret: raise Exception("Critical environment variables are missing for ZusBackendService") return ZusBackendService(base_uri, client_name, client_secret) @order_router.get("/order-details/{order_id}") async def order_details(order_id: str, zus_service: ZusBackendService = Depends(get_zus_service)): order_details = zus_service.get_order_details({"order_no": order_id}) if not order_details: raise HTTPException(status_code=404, detail="Order not found") return order_details @order_router.post("/", response_model=ChatResponseSchema, status_code=201) def create_chat_orders(chat: ChatCreateSchema, db: Session = Depends(get_db)): new_chat = Chat(**chat.dict()) db.add(new_chat) db.commit() db.refresh(new_chat) return new_chat @order_router.get("/", response_model=List[ChatResponseSchema]) def read_chats_orders(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): chats = db.query(Chat).offset(skip).limit(limit).all() return chats @order_router.get("/{chat_id}", response_model=ChatResponseSchema) def read_chats_orders(chat_id: int, db: Session = Depends(get_db)): chat = db.query(Chat).filter(Chat.id == chat_id).first() if chat is None: raise HTTPException(status_code=404, detail="Chat not found") return chat @order_router.get("/check_order/{order_id}", status_code=200) def check_order(order_id: int, db: Session = Depends(get_db)): """API endpoint to check if an order exists.""" # Check directly if an order exists by querying the Chat table. order_exists = db.query(Chat).filter(Chat.order_id == order_id).first() is not None if order_exists: return {"message": "Order exists."} else: raise HTTPException(status_code=404, detail="Order not found")
问题原因及修复方案
sys.path 路径错误
你添加的/routers/chat_order_router是系统根目录的绝对路径,并非项目内的routers目录。而且无需添加单个文件的路径,只需保证项目根目录在Python的搜索路径中即可。修复后的main.py代码
由于main.py在项目根目录,routers是根目录的子目录,直接通过常规导入方式即可:from fastapi import FastAPI # 直接从routers目录导入,无需修改sys.path from routers.chat_order_router import order_router app = FastAPI() app.include_router(order_router) @app.get("/") def read_root(): return {"Hello": "World"}额外检查项
- 确认运行
fastapi run时,当前工作目录是项目根目录(即main.py所在目录),否则需用fastapi run ./main.py指定文件路径。 - 检查虚拟环境是否激活,避免因环境不一致导致模块找不到。
- 确认运行
内容的提问来源于stack exchange,提问作者balron
相关产品推荐
相关产品推荐

