FastAPI基础之 接入FastFdfs文件服务器操作文件
2021/6/8 18:27:40
本文主要是介绍FastAPI基础之 接入FastFdfs文件服务器操作文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
接入FastFdfs文件服务器操作文件,直接上源码
@author: xxx
@file: views.py
@time: 2021/5/27 11:10
@desc: 文件管理
"""
from typing import List
from fastapi import APIRouter, Depends, BackgroundTasks, HTTPException, Form, File, UploadFile
from server import config
from sqlalchemy.orm import Session
from starlette.responses import RedirectResponse
from starlette.requests import Request
from server.schemas.base import HttpResponseModel
from server.app_file.models.file import BaseFile
from server.utils.database import get_db
from server.utils import check_file
from server.utils.responses import response_code_set
from server.utils.dependencies import verify_token
from fdfs_client.client import *
fds_config = get_tracker_conf(config.FILE_CONF)
client = Fdfs_client(fds_config)
router = APIRouter()
@router.post(
"/upload/",
tags=["文件上傳"],
responses=response_code_set({"code": 200,
"message": "文件上传成功",
"content": {
"name": "20210501截图.jpg",
"path": "http://47.105.39.143:20000/group1/M00/00/35/rB88YAAJH0UfP0aY397.jpg",
"type": "jpg",
"size": "145.95KB",
"notes": "20210501截图.jpg",
"id": 2
}
})
)
async def views_base(
file: UploadFile = File(...), # 接收文件流
db: Session = Depends(get_db) # 实例数据库对象
):枣庄妇科医院哪家好 http://mobile.0632dffk.com/
code, content, message = 200, {}, u''
try:
if not file:
code, content, message = 404, {}, u'file 缺失'
elif not check_file.check_file_type(file.filename, 'file_all'):
code, content, message = 404, {}, u'不允许的文件格式'
elif not check_file.check_file_size(file.spool_max_size, 'file'):
code, content, message = 404, {}, u'文件大小超出服务器限制'
else:
file_name = file.filename # 文件名
file_type = file_name.split('.')[1] # 文件类型
ret = client.upload_by_buffer(file.file.read(), file_type) # 调用fastfdfs上传文件流
remote_file_id = str(ret['Remote file_id'], encoding='utf8') # 拿到返回值
path = config.FILE_SERVER_IP + ':' + config.FILE_DOWNLOAD_PORT + '/' + remote_file_id # 拼接返回值
size = ret['Uploaded size'] # 文件大小
# 将信息入库
file_obj = await BaseFile.insert(db=db, name=file_name, path=path, type=file_type, size=size,
notes=file_name)
code, content, message = 200, file_obj, u'文件上传成功'
except Exception as e:
code, content, message = 405, {}, u'上传失败:{}'.format(e)
finally:
return HttpResponseModel(code=code, message=message, content=content)
这篇关于FastAPI基础之 接入FastFdfs文件服务器操作文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Java语音识别项目资料:新手入门教程
- 2024-11-26JAVA语音识别项目资料:新手入门教程
- 2024-11-26Java语音识别项目资料:入门与实践指南
- 2024-11-26Java云原生资料入门教程
- 2024-11-26Java云原生资料入门教程
- 2024-11-26Java云原生资料:新手入门教程
- 2024-11-25Java创意资料:新手入门的创意学习指南
- 2024-11-25JAVA对接阿里云智能语音服务资料详解:新手入门指南
- 2024-11-25Java对接阿里云智能语音服务资料详解
- 2024-11-25Java对接阿里云智能语音服务资料详解