python 项目相关

python 项目相关

python -m venv venv

这条命令的作用是,在当前路径下 生成一个 venv 文件夹,并运行 python 的 venv 模块,用于依赖隔离。

  • 命令执行后,会在当前文件下 生成一个 venv/ 的文件夹
    python -m venv venv

  • python 当前环境的 python 解释器

  • -m venv 运行 python 的 venv 模块 ( -m xxx 运行 python 的 xxx 模块)

  • venv 虚拟环境目录名,主要用于区分不同项目,可以随意起。

复制代码
venv/
├── bin/            # 可执行文件(macOS / Linux)
│   ├── python
│   ├── pip
│   └── activate
├── lib/
│   └── python3.x/
│       └── site-packages/
├── include/
└── pyvenv.cfg

source venv/bin/activate 虚拟环境激活

bash 复制代码
source venv/bin/activate

# 激活成功
(venv) $

which python 查看 python 指向的虚拟环境

bash 复制代码
which python

安装依赖只会影响当前项目

bash 复制代码
pip install requests

安装到 venv/lib/python3.x/site-packages/

deactivate 退出虚拟环境

bash 复制代码
deactivate

pip list 快速查看当前项目的 python 依赖

Fastapi 项目启动

写一个最小服务

python 复制代码
from fastapi import FastAPI
app = FastAPI()

@app.get('/health')
def health_check():
    return {status:'ok',content:'hello world'}

项目启动

bash 复制代码
uvicorn main:app --reload

页面访问

服务启动后可以访问的地址:

Pydantic 数据模型

pydantic 会对输入的变量类型进行约束,如果不符合定义的变量类型,就会报如下错误

复制代码
{
    "detail": [
        {
            "type": "string_type",
            "loc": [
                "body",
                "name"
            ],
            "msg": "Input should be a valid string",
            "input": 123
        },
        {
            "type": "int_parsing",
            "loc": [
                "body",
                "age"
            ],
            "msg": "Input should be a valid integer, unable to parse string as an integer",
            "input": "asdf"
        }
    ]
}
python 复制代码
from pydantic import BaseModel

class greetUserRequestModel(BaseModel):
    name: str
    age: int


class greetUserResponseModel(BaseModel):
    message: str
    age_in_5_years: int


@app.post("/greet", response_model=greetUserResponseModel)
def greet_user(request: greetUserRequestModel):
    message = f"Hello, {request.name}!"
    age_in_5_years = request.age + 5
    return greetUserResponseModel(message=message, age_in_5_years=age_in_5_years)
相关推荐
copyer_xyf2 小时前
Agent RAG
后端·python·agent
copyer_xyf2 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf2 小时前
Agent 记忆管理
后端·python·agent
星云穿梭18 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵18 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠1 天前
大模型之LangGraph技术体系
python·llm
hboot2 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python