Using Fastdfs in a Django project

Source: Internet
Author: User
Tags builtin virtual environment

FASTDFS Client with custom file storage System1. Fastdfs's Python client

Python version of Fastdfs client usage Instructions Reference https://github.com/jefforeilly/fdfs_client-py

installation

Install the Fdfs_client-py-master.zip into a virtual environment for everyone

Pip Install Fdfs_client-py-master.zip
Pip Install Mutagen
PIP Isntall Requests
Use

With the Fastdfs client, a configuration file is required. We create a new Fastdfs directory under the Meiduo_mall/utils directory and place the client.conf configuration file provided to you in this directory.

Need to modify the client.conf configuration file

Base_path=Fastdfs The directory where the client holds the log files
tracker_server= machine IP for running tracker service:22122

Uploading a file requires creating a Fdfs_client.client.Fdfs_client object and indicating the configuration file, such as

Fdfs_client.   fdfs_client
Fdfs_client (' meiduo_mall/utils/fastdfs/client.conf ')

How to upload a file by creating a client object

Client. upload_by_filename ( file name)
Or
Client. upload_by_buffer ( file bytes data)

Such as:

>>>RET =Client.Upload_by_filename ('/users/delron/desktop/1.png ')
GettingConnection
<Fdfs_client.Connection.ConnectionObjectAt0x1098d4cc0>
<Fdfs_client.Fdfs_protol.tracker_header object at 0x1098d4908>
>>> ret
{ ' Group name ': ' group1 ', ' Remote file_id ': ' group1/m00/00/02/ctm3bvr-k6sacjaiaajctr1enna809.png ', ' Upload successed. ', ' Local File name ': '/users/delron/desktop/1.png ', ' uploaded size ': ' 151.00KB ', ' Storage IP ': ' 10.211.55.5 '}
>>>
    • Remote file_id is the path to the Fastdfs saved file

2. Customizing the Django file storage System

While learning the Django framework, we've already said that Django comes with a file storage system, but the default file is stored locally, and in this project we need to save the file to the Fastdfs server, so we need to customize the file storage System.

Here's how to customize your file storage System:

1) need to inherit from django.core.files.storage.Storage , as

Django. Core. files.   Storage
?
Fastdfsstorage (Storage):
...

2) Support Django to instantiate the storage class without any parameters, i.e. any settings should be taken from django.conf.settings

1  fromDjango.confImportSettings2  fromDjango.core.files.storageImportStorage3 ?4 classfasfdfsstorage (Storage):5     def __init__(Self, Base_url=none, client_conf=None):6         ifBase_url isNone:7Base_url =settings. Fdfs_url8Self.base_url =Base_url9         ifClient_conf isNone:Tenclient_conf =settings. Fdfs_client_conf Oneself.client_conf = client_conf

3) Storage classes must be implemented _open() and _save() methods, and any subsequent use may be used in other methods.

  • _open(name, mode=‘rb‘)

    Called by the Storage.open () and is used when the file is opened.

  • _save(name, content)

    Called by Storage.save (), name is the incoming file name, content is the file contents that Django receives, and the method needs to save the content file contents.

    Django saves the method's return value to the corresponding file field in the database, which means that the method should return the file name information to be saved in the database.

  • exists(name)

    Returns true if a file named name exists in the file system, otherwise false is returned.

  • url(name)

    Returns the full access URL of the file

  • delete(name)

    Delete the file name

  • listdir(path)

    Lists the contents of the specified path

  • size(name)

    Returns the total size of the name file

    Note that not all of these methods are implemented, and you can omit methods that are not available.

4) need to add django.utils.deconstruct.deconstructible adorners for storage class

We create a fdfs_storage.py file in the Meiduo_mall/utils/fastdfs directory to implement storage classes that can use Fastdfs to store files as follows

1  fromDjango.confImportSettings2  fromDjango.core.files.storageImportStorage3  fromDjango.utils.deconstructImportdeconstructible4  fromFdfs_client.clientImportfdfs_client5 ?6 ?7 @deconstructible8 classfasfdfsstorage (Storage):9     def __init__(Self, Base_url=none, client_conf=None):Ten         """ One Initialize A :p Aram Base_url: The domain name of the image server used to construct the full path of the picture - :p The path to the Aram Client_conf:fastdfs client configuration file -         """ the         ifBase_url isNone: -Base_url =settings. Fdfs_url -Self.base_url =Base_url -         ifClient_conf isNone: +client_conf =settings. Fdfs_client_conf -self.client_conf =client_conf + ? A     def_open (self, name, mode='RB'): at         """ - Open file is not available, so omit -         """ -         Pass - ? -     def_save (self, Name, content): in         """ - save a file in Fastdfs to :p Aram Name: The file name passed in + :p Aram Content: File contents - : Return: File name of the Fastdfs saved to the database the         """ *Client =fdfs_client (self.client_conf) $RET =Client.upload_by_buffer (Content.read ())Panax Notoginseng         ifRet.get ("Status") !="Upload successed.": -             RaiseException ("Upload file failed") thefile_name = Ret.get ("Remote file_id") +         returnfile_name A ? the     defURL (self, name): +         """ - returns the full URL path of the file $ :p Aram Name: The file name saved in the database $ : return: Full URL -         """ -         returnSelf.base_url +name the ? -     defexists (self, name):Wuyi         """ the determine whether the file exists, Fastdfs can solve the problem of the name of the file itself - so return false here and tell Django that all the new files are being uploaded Wu :p Aram Name: file name - : Return:false About         """ $         returnFalse

3. Setting the custom file storage class in the Django configuration

Adding settings to the settings/dev.py file

# Django file storage, specifying a custom file storage System ' Meiduo_mall.utils.fastdfs.fdfs_storage. Fastdfsstorage'? # Fastdfs ' http://image.meiduo.site:8888/ ' ' utils/fastdfs/client.conf')    

4. Add an image domain name

Add a domain name to the/etc/hosts to access the Fastdfs storage server

127.0.0.1 Image.meiduo.site

Using Fastdfs in a Django project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.