【FastAPI基础】17.1、接入FastFdfs文件服务器操作文件,附源码

22 篇文章 23 订阅

引言:

最近工作中有机会接触FastAPI这个框架,所以就把官方文档看了一遍,对框架的各个特性及使用方法做了总结,会逐步的发出来,希望对您有用。

如果您之前接触过python的其他框架,看起来会非常简单和顺畅,其实就是很简单。

【上一篇】:【FastAPI基础】17、文件操作
【下一篇】:【FastAPI基础】18、表单和文件操作
【FastAPI搭建好的产品框架源码,直接上手】:【FastAPI搭建好的产品架构】,直接上手

废话不多说,直接上源码,复制直接用呗,其他的就不粘贴了,没啥特别的。
如有需要help,下面私信我

# encoding: utf-8
"""
@author: 陈建华
@file: views.py
@time: 2021/2/17 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": "QQ截图20201111104820.jpg",
                                     "path": "http://47.105.39.143:20000/group1/M00/00/35/rB88YAAJH0UfP0aY397.jpg",
                                     "type": "jpg",
                                     "size": "145.95KB",
                                     "notes": "QQ截图20201111104820.jpg",
                                     "id": 2
                                 }
                                 })
)
async def views_base(
        file: UploadFile = File(...),		# 接收文件流
        db: Session = Depends(get_db)		# 实例数据库对象
):
    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)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
文本格式不能很好显示,请见谅(件里有比较齐整的excel表格统计) 大小类型 传输类型 api方法 文件大小 花费时间 速率byte/ms 速率mb/s 缓存数组 次数 备注 大文件 下载 download_file(group_name, remote_filename, localFile) 1073741824(约1G) 28343ms 37883 36.12804413 无 1 下载 download_file(group_name, remote_filename , downloadStream) 1073741824(约1G) 29195ms 36778 35.07423401 0 1 fastDFS的DownloadStream,FileOutputStream 下载 download_file(group_name, remote_filename , downloadStream) 1073741824(约1G) 24352ms 44092 42.04940796 2K 1 fastDFS的DowloadStream,BufferedOutputStream 下载 download_file(group_name, remote_filename , DownloadCallback) 1073741824(约1G) 24831ms 43241 41.23783112 2K 1 实现DownloadCallback,BufferedOutputStream 下载 download_file(group_name, remote_filename , DownloadCallback) 1073741824(约1G) 25922ms 41422 39.50309753 8K 1 实现DownloadCallback,BufferedOutputStream 普通文件 下载 download_file(group_name, remote_filename, localFile) 59113472(约56M) 382ms 154747 147.5782394 无 1 下载 download_file(group_name, remote_filename , downloadStream) 59113472(约57M) 369ms 160199 152.7776718 0 1 fastDFS的DownloadStream,FileOutputStream 下载 download_file(group_name, remote_filename , downloadStream) 59113472(约58M) 499ms 118702 113.2030487 2K 1 fastDFS的DowloadStream,BufferedOutputStream 下载 download_file(group_name, remote_filename , DownloadCallback) 59113472(约59M) 592ms 99853 95.22724152 2K 1 实现DownloadCallback,BufferedOutputStream 下载建议:100M内数据使用fastDFS提供的DownloadStream;大于1G的数据,使用BufferedOutputStream和DowloadStream
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈建华呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值