zoukankan      html  css  js  c++  java
  • django中使用FastDFS分布式文件系统接口代码实现文件上传、下载、更新、删除

    运维使用docker部署好之后FastDFS分布式文件系统之后,提供给我接口如下:

    fastdfs  tracker 192.168.1.216   192.168.1.217  storage 192.168.1.216  192.168.1.217

    我们只需要在配置文件中进行配置即可,然后利用客户端提供的接口通过简单的代码就可以将文件上传到分布式文件系统中

    至于内部实现机制,可以参考我的另外一篇博客:分布式文件系统Fastdfs原理及部署

    再次提醒在安装客户端可能会遇到各种不可控的因素,导致你上传失败,在windows中在进行安装客户端fdfs_client模块或在linux安装fdsff_client模块之后,在使用接口时都可能会出现问题,小伙伴们可以在使用时自行踩坑,我只介绍我踩坑之后最终的实现方法,即可绕过踩坑,介绍流程包括fastdfs客户端的安装、配置、django中调用相应的接口

    一、客户端Fastdfs客户端的安装

    因客户端模块在自行安装会出现问题,所以我提供该客户端的模块,下载链接:fast_client模块

    进入fdfs_client-py-master.zip所在目录

    pip install fdfs_client-py-master.zip
    
    pip install mutagen
    
    pip install requests

    配置文件在django项目中的存放位置:

    配置文件client.conf中的内容个如下,需要做修改的部分已用红色进行标注:

    # connect timeout in seconds
    # default value is 30s
    connect_timeout=30
    
    # network timeout in seconds
    # default value is 30s
    network_timeout=60
    
    # the base path to store log files
    #客户端存放日志目录,可自行设置
    base_path=/Users/delron/Desktop
    
    # tracker_server can ocur more than once, and tracker_server format is
    #  "host:port", host can be hostname or ip address
    #改成自己的ip即可,配置一个即可tracker会自行帮助我们进行任务调度
    tracker_server=192.168.1.217:22122
    
    #standard log level as syslog, case insensitive, value list:
    ### emerg for emergency
    ### alert
    ### crit for critical
    ### error
    ### warn for warning
    ### notice
    ### info
    ### debug
    log_level=info
    
    # if use connection pool
    # default value is false
    # since V4.05
    use_connection_pool = false
    
    # connections whose the idle time exceeds this time will be closed
    # unit: second
    # default value is 3600
    # since V4.05
    connection_pool_max_idle_time = 3600
    
    # if load FastDFS parameters from tracker server
    # since V4.05
    # default value is false
    load_fdfs_parameters_from_tracker=false
    
    # if use storage ID instead of IP address
    # same as tracker.conf
    # valid only when load_fdfs_parameters_from_tracker is false
    # default value is false
    # since V4.05
    use_storage_id = false
    
    # specify storage ids filename, can use relative or absolute path
    # same as tracker.conf
    # valid only when load_fdfs_parameters_from_tracker is false
    # since V4.05
    storage_ids_filename = storage_ids.conf
    
    
    #HTTP settings
    http.tracker_server_port=80
    
    #use "#include" directive to include HTTP other settiongs
    ##include http.conf

    二、在djaogo中使用fastdf接口实现增、删、改,下载

    自定义文件,以下仅供参考:

    以下是实现分布式文件系统实现文件的上传、修改、删除的代码:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2019/4/26 10:09
    # @Author  : suihongliang
    # @Site    : 
    # @File    : fastdfs_service.py
    # @Software: PyCharm
    """
    使用fastdfs分布式文件存储系统实现文件的上传、下载、删除
    """
    from django.conf import settings
    from django.core.files.storage import Storage
    from django.utils.deconstruct import deconstructible
    from fdfs_client.client import Fdfs_client
    from utils.logger_utils import get_logging
    
    logger = get_logging(__name__)
    
    
    @deconstructible
    class FastDFSStorage(Storage):
        def __init__(self, client_conf=None):
            """
            初始化
            :param client_conf: FastDFS客户端配置文件的路径
            """
            if client_conf is None:
                client_conf = settings.FDFS_CLIENT_CONF
            self.client_conf = client_conf
    
        # def upload(self, content):
        #     """
        #     在FastDFS中保存文件
        #     :param content: 通过
        #     :return: 保存到数据库中的FastDFS的文件名
        #     """
        #     client = Fdfs_client(self.client_conf)
        #     ret = client.upload_by_buffer(content.read())
        #     if ret.get("Status") != "Upload successed.":
        #         raise Exception("upload file failed")
        #     file_name = ret.get("Remote file_id")
        #     return file_name
    
        def upload(self, local_path):
            """
            将文件上传到fastdfs分布式文件系统中
            :param local_path: 上传文件的本地路径
            :return:
            """
            client = Fdfs_client(self.client_conf)
            ret = client.upload_by_file(local_path)
            logger.info(ret)
            print(ret)
            if ret.get("Status") != "Upload successed.":
                raise Exception("upload file failed")
            remote_file_id = ret.get("Remote file_id")
            logger.info("存储在fastdfs上的文件路径:", remote_file_id)
    
            return True, remote_file_id
    
        def update(self, local_path, remote_file_id):
            """
            对修改后的文件进行更新
            :param local_path:
            :param remote_file_id:
            @return: dictionary {
                'Status'     : 'Modify successed.',
                'Storage IP' : storage_ip
            }
            """
            client = Fdfs_client(self.client_conf)
            try:
                local_path=bytes(local_path.encode("utf-8"))
                remote_file_id=bytes(remote_file_id.encode("utf-8"))
                ret_update = client.modify_by_file(local_path, remote_file_id)
                logger.info("文件更新成功",ret_update)
                return True, ret_update
            except Exception as e:
                logger.warning(u'文件更新失败,错误信息:%s' % repr(e))
                return None, "文件更新失败"
    
        def download(self, local_path, remote_file_id):
            """
            从fastdfs分布式文件系统进行下载文件
            :param local_path: 本地保存文件路径
            :param remote_file_id: 上传到fastdfs文件系统中自动生成的文件路径即文件id
            @return dict {
                'Remote file_id'  : remote_file_id,
                'Content'         : local_filename,
                'Download size'   : downloaded_size,
                'Storage IP'      : storage_ip
            }
            """
            client = Fdfs_client(self.client_conf)
            try:
                ret_download = client.download_to_file(local_path, remote_file_id)
                return True, ret_download
    
            except Exception as e:
                logger.warning(u'文件下载失败,错误信息:%s' % repr(e))
                return None, "文件下载失败"
    
        def delete(self, remote_file_id):
            """
            从fastdfs分布式文件系统中将文件删除
            :param remote_file_id: 上传到fastdfs文件系统中自动生成的文件路径即文件id
            @return tuple ('Delete file successed.', remote_file_id, storage_ip)
            """
            client = Fdfs_client(self.client_conf)
            try:
                ret_delete = client.delete_file(remote_file_id)
                return ret_delete
    
            except Exception as e:
                logger.warning(u'文件删除失败,错误信息:%s' % repr(e))
                return None

    在django创建的settings中需要做的配置信息如下:

    可以根据自己代码实现进行相应的配置:

    # fastdf配置文件设置
    #
    DEFAULT_FILE_STORAGE = 'distributedstorage.utils.fastdfs.fdfs_storage.FastDFSStorage'
    
    # FastDFS
    # fastdfs  tracker 192.168.1.212   192.168.1.213  storage 192.168.1.212  192.168.1.213
    # FDFS_CLIENT_CONF = os.path.join(BASE_DIR, 'utils/fastdfs/client.conf')
    FDFS_CLIENT_CONF = os.path.join(BASE_DIR, 'client.conf')

    在调用接口时,传递相应的参数即可完成文件的上传、下载、删除和更新,成功使用客户端进行文件的增、删、改和下载后返回文件的参数见上述代码。

    原创不易,转载需说明,希望对你有所帮助!

  • 相关阅读:
    odoo11 外部数据导入方法2
    odoo 11 实现多个字段对应一个查询参数的查询
    ionic 访问odoo11之具体业务类api接口
    ionic访问odoo 11接口
    odoo 11导入外部数据过程记录
    程序发送邮件的思考
    Topshelf的Ioc实现
    查看MS Sqlserver文件大小语句
    TopShelf 自动配置Service测试
    odoo11 添加自定义模块报错问题
  • 原文地址:https://www.cnblogs.com/sui776265233/p/10795188.html
Copyright © 2011-2022 走看看