FastAPI上传文件接口及上传代码使用gunicorn进行启动

服务器端代码:

代码说明:首次是创建了一个upload的url,指向的是upload_file方法,这个方法里面获取了文件的名称,然后重命名了文件名,最后把这个文件保存到执行的位置,默认就是当前目录下,最后给返回文件名

main.py

from fastapi import FastAPI, UploadFile

app = FastAPI()


@app.post("/upload/")
async def upload_file(file: UploadFile):
    file_name = file.filename
    print(file_name)

    file_name = '2333.xlsx'
    # 保存文件到指定位置
    with open(file_name, "wb") as f:
        f.write(file.file.read())

    return {"filename": file_name}


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host='192.168.0.2', port=7799)

客户端请求代码:

import requests


if __name__ == '__main__':
    url = "http://192.168.0.2:7799/upload/"
    file_path = "测试数据.xlsx"

    with open(file_path, "rb") as file:
        files = {"file": file}
        response = requests.post(url, files=files)

    print(response.json())

使用 gunicorn 进行进程守护及监控:

gunicorn.py

import os.path
import multiprocessing

daemon = True
bind = '127.0.0.1:7799'  # 配置你的IP和端口
pidfile = '/var/run/gunicorn.pid'
base_path = '/root/data_test' # 配置项目目录
chdir = os.path.join(base_path, 'file_master')  # 工作目录
worker_class = 'uvicorn.workers.UvicornWorker'
#workers = 10  # 设置worker数,一般采用下方的方法
workers=multiprocessing.cpu_count()+1
threads = 2
loglevel = 'info'  # 日志级别
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
accesslog = os.path.join(base_path, 'logs', 'gunicorn_access.log')
errorlog = os.path.join(base_path, 'logs', 'gunicorn_error.log')

启动服务,建议写成shell脚本,与gunicorn放置同一处

start.sh

# 需要把main替换成你的主文件,app替换为主文件里面的FastAPI对象名称,如果你的命名和上述一样可直接使用
gunicorn main:app -c gunicorn.py

启动后,可以通过 ps -ef|grep gunicorn main:app 查看进程情况,因为设置了多worker,会导致有很多进程,关闭服务时可以通过以下命令批量关闭:

stop.sh

# 引号里面的数据取决于你开始任务的脚本,要保持一致

pkill -f "gunicorn main:app"

你可能感兴趣的:(FastAPI,fastapi)