以windows系统为例
安装python
官网下载安装包:https://www.python.org/
开始写代码
新建一个目录PythonProject1
新建一个文件main.py
# FastAPI 和 OpenAI DEMO
from openai import OpenAI
from fastapi import FastAPI, Query
from fastapi.staticfiles import StaticFiles
from fastapi import applications
from fastapi.openapi.docs import get_swagger_ui_html
from pydantic import BaseModel
from typing import List
def swagger_monkey_patch(*args, **kwargs):
return get_swagger_ui_html(
*args,
**kwargs,
swagger_js_url="/static/swagger/swagger-ui-bundle.js",
swagger_css_url="/static/swagger/swagger-ui.css"
)
applications.get_swagger_ui_html = swagger_monkey_patch
app = FastAPI()
# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")
client = OpenAI(
api_key="xxxxx",
base_url="https://open.bigmodel.cn/api/paas/v4/",
)
# 定义数据模型
class Message(BaseModel):
role: str
content: str
@app.post("/getSQLMultiRound")
async def get_sql_multi_round(messages: List[Message]):
completion = client.chat.completions.create(
model="glm-4-plus", ## deepseek-reasoner / deepseek-chat
messages=messages,
temperature=0,
stream=False,
)
res = completion.choices[0].message.content
return {"sql": res, "message": completion.choices[0].message}
运行
安装依赖:
pip install openai
pip install fastapi
安装web服务器:pip install uvicorn
运行这个web项目:uvicorn main:app --host 0.0.0.0 --port 8000
浏览器打开:http://127.0.0.1:8000/docs 就可以了
部署到服务器
### 安装包管理器
pip install pipenv
### 生成requirements.txt
### 项目统一使用pipenv进行包管理,然后就可以用下面的命令生成requirements.txt
pipenv requirements > requirements.txt
### 下载依赖包到packages目录
pip download -r requirements.txt -d packages
### 生产环境安装依赖包
### 把packages目录上传到服务器,执行下面命令进行安装:
pip install --no-index --find-links=packages -r requirements.txt
虚拟环境
先在项目跟目录下创建 【.venv】目录
命令行执行: pipenv --python 3.13.2 启用虚拟环境
会把项目需要的依赖包等文件下载到.venv目录,实现不同的项目使用不用的python版本