تطوير ملفات Azure باستخدام Python

تعرف على أساسيات استخدام Python لتطوير التطبيقات أو الخدمات التي تستخدم Azure Files لتخزين بيانات الملفات. أنشئ تطبيقا بسيطا لوحدة التحكم وتعرف على كيفية تنفيذ الإجراءات الأساسية باستخدام ملفات Python وAzure:

  • إنشاء أسهم ملفات Azure
  • إنشاء دلائل
  • تعداد الملفات والدلائل في مشاركة ملف Azure
  • تحميل وتنزيل وحذف ملف
  • إنشاء نسخ احتياطية لمشاركة الملفات باستخدام لقطات

ملاحظة

نظرا لأنه يمكن الوصول إلى ملفات Azure عبر SMB، فمن الممكن كتابة تطبيقات بسيطة يمكن الوصول إلى مشاركة ملف Azure باستخدام فئات Python I/O القياسية ووظائفها. ستوضح هذه المقالة كيفية كتابة التطبيقات التي تستخدم Azure Storage ++C SDK، والتي تستخدم File REST APIللتحدث إلى ملفات Azure.

ينطبق على

نوع مشاركة الملف SMB NFS
مشاركات الملفات القياسية (GPv2)، LRS/ZRS Yes No
مشاركات الملفات القياسية (GPv2)، GRS/GZRS Yes No
مشاركات الملفات المتميزة (FileStorage)، LRS/ZRS Yes No

تنزيل وتثبيت Azure Storage SDK لـ Python

ملاحظة

إذا كنت تقوم بالترقية من Azure Storage SDK لـ Python الإصدار 0.36 أو إصدار أقدم، فقم بإزالة تثبيت حزمة SDK الأقدم باستخدام pip uninstall azure-storage قبل تثبيت أحدث حزمة.

مكتبة العميل Azure Files v12.x لـ Pythonتتطلب الإصدار 2.7 أو 3.6+.

التثبيت عبر فهرس حزمة بايثون

للتثبيت عبر فهرس حزمة بايثون، اكتب:

pip install azure-storage-file-share

إعداد تطبيقك لاستخدام ملفات Azure

أضف ما يلي بالقرب من أعلى ملف مصدر بايثون لاستخدام القصاصات البرمجية في هذه المقالة.

from azure.core.exceptions import (
    ResourceExistsError,
    ResourceNotFoundError
)

from azure.storage.fileshare import (
    ShareServiceClient,
    ShareClient,
    ShareDirectoryClient,
    ShareFileClient
)

إعداد اتصال بملفات Azure

يتيح لك ShareServiceClient العمل مع المشاركات والدلائل والملفات. التعليمة البرمجية التالية بإنشاء كائن ShareServiceClient باستخدام سلسلة اتصال حساب التخزين.

# Create a ShareServiceClient from a connection string
service_client = ShareServiceClient.from_connection_string(connection_string)

إنشاء مشاركة ملف Azure

يستخدم مثال التعليمة البرمجية التالي كائن ShareClient لإنشاء المشاركة إذا لم تكن موجودة.

def create_file_share(self, connection_string, share_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        print("Creating share:", share_name)
        share_client.create_share()

    except ResourceExistsError as ex:
        print("ResourceExistsError:", ex.message)

إنشاء دليل

يمكنك تنظيم التخزين عن طريق وضع الملفات داخل الدلائل الفرعية بدلا من وجودها جميعا في الدليل الجذر.

الطريقة التالية تنشئ دليلاً في جذر مشاركة الملفات المحددة باستخدام كائن ShareDirectoryClient.

def create_directory(self, connection_string, share_name, dir_name):
    try:
        # Create a ShareDirectoryClient from a connection string
        dir_client = ShareDirectoryClient.from_connection_string(
            connection_string, share_name, dir_name)

        print("Creating directory:", share_name + "/" + dir_name)
        dir_client.create_directory()

    except ResourceExistsError as ex:
        print("ResourceExistsError:", ex.message)

تحميل ملف

في هذا القسم، ستتعرف على كيفية تحميل ملف من وحدة التخزين المحلية إلى ملفات Azure.

تقوم الطريقة التالية بتحميل محتويات الملف المحدد إلى الدليل المحدد في مشاركة ملف Azure المحددة.

def upload_local_file(self, connection_string, local_file_path, share_name, dest_file_path):
    try:
        source_file = open(local_file_path, "rb")
        data = source_file.read()

        # Create a ShareFileClient from a connection string
        file_client = ShareFileClient.from_connection_string(
            connection_string, share_name, dest_file_path)

        print("Uploading to:", share_name + "/" + dest_file_path)
        file_client.upload_file(data)

    except ResourceExistsError as ex:
        print("ResourceExistsError:", ex.message)

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

تعداد الملفات والدلائل في مشاركة ملف Azure

لسرد الملفات والدلائل في دليل فرعي، استخدم طريقة list_directories_and_files. ترجع هذه الطريقة إمكانية تكرار ترحيل الصفحات التلقائي. تقوم التعليمة البرمجية التالية بإخراج اسم كل ملف ودليل فرعي في الدليل المحدد إلى وحدة التحكم.

def list_files_and_dirs(self, connection_string, share_name, dir_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        for item in list(share_client.list_directories_and_files(dir_name)):
            if item["is_directory"]:
                print("Directory:", item["name"])
            else:
                print("File:", dir_name + "/" + item["name"])

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

تنزيل ملف

لتنزيل بيانات من ملف، استخدم download_file.

يوضح المثال التالي الاستخدام download_file للحصول على محتويات الملف المحدد وتخزينه محليا باستخدام DOWNLOADED- مسبوق باسم الملف.

def download_azure_file(self, connection_string, share_name, dir_name, file_name):
    try:
        # Build the remote path
        source_file_path = dir_name + "/" + file_name

        # Add a prefix to the filename to 
        # distinguish it from the uploaded file
        dest_file_name = "DOWNLOADED-" + file_name

        # Create a ShareFileClient from a connection string
        file_client = ShareFileClient.from_connection_string(
            connection_string, share_name, source_file_path)

        print("Downloading to:", dest_file_name)

        # Open a file for writing bytes on the local system
        with open(dest_file_name, "wb") as data:
            # Download the file from Azure into a stream
            stream = file_client.download_file()
            # Write the stream to the local file
            data.write(stream.readall())

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

إنشاء لقطة مشاركة

يمكنك إنشاء نسخة زمنية من مشاركة الملف بالكامل.

def create_snapshot(self, connection_string, share_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        # Create a snapshot
        snapshot = share_client.create_snapshot()
        print("Created snapshot:", snapshot["snapshot"])

        # Return the snapshot time so 
        # it can be accessed later
        return snapshot["snapshot"]

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

قائمة المشاركات واللقطات

يمكنك سرد جميع اللقطات لمشاركة معينة.

def list_shares_snapshots(self, connection_string):
    try:
        # Create a ShareServiceClient from a connection string
        service_client = ShareServiceClient.from_connection_string(connection_string)

        # List the shares in the file service
        shares = list(service_client.list_shares(include_snapshots=True))

        for share in shares:
            if (share["snapshot"]):
                print("Share:", share["name"], "Snapshot:", share["snapshot"])
            else:
                print("Share:", share["name"])

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

استعراض لقطة المشاركة

يمكنك استعراض كل لقطة مشاركة لاسترداد الملفات والدلائل من تلك النقطة الزمنية.

def browse_snapshot_dir(self, connection_string, share_name, snapshot_time, dir_name):
    try:
        # Create a ShareClient from a connection string
        snapshot = ShareClient.from_connection_string(
            conn_str=connection_string, share_name=share_name, snapshot=snapshot_time)

        print("Snapshot:", snapshot_time)

        for item in list(snapshot.list_directories_and_files(dir_name)):
            if item["is_directory"]:
                print("Directory:", item["name"])
            else:
                print("File:", dir_name + "/" + item["name"])

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

الحصول على ملف من لقطة المشاركة

يمكنك تنزيل ملف من لقطة مشاركة. هذا يمكنك من استعادة إصدار سابق من ملف.

def download_snapshot_file(self, connection_string, share_name, snapshot_time, dir_name, file_name):
    try:
        # Build the remote path
        source_file_path = dir_name + "/" + file_name

        # Add a prefix to the local filename to 
        # indicate it's a file from a snapshot
        dest_file_name = "SNAPSHOT-" + file_name

        # Create a ShareFileClient from a connection string
        snapshot_file_client = ShareFileClient.from_connection_string(
            conn_str=connection_string, share_name=share_name, 
            file_path=source_file_path, snapshot=snapshot_time)

        print("Downloading to:", dest_file_name)

        # Open a file for writing bytes on the local system
        with open(dest_file_name, "wb") as data:
            # Download the file from Azure into a stream
            stream = snapshot_file_client.download_file()
            # Write the stream to the local file
            data.write(stream.readall())

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

حذف لقطة مشاركة واحدة

يمكنك حذف لقطة مشاركة واحدة.

def delete_snapshot(self, connection_string, share_name, snapshot_time):
    try:
        # Create a ShareClient for a snapshot
        snapshot_client = ShareClient.from_connection_string(conn_str=connection_string, share_name=share_name, snapshot=snapshot_time)

        print("Deleting snapshot:", snapshot_time)

        # Delete the snapshot
        snapshot_client.delete_share()

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

حذف ملف

لحذف ملف، استدعي delete_file.

def delete_azure_file(self, connection_string, share_name, file_path):
    try:
        # Create a ShareFileClient from a connection string
        file_client = ShareFileClient.from_connection_string(
            connection_string, share_name, file_path)

        print("Deleting file:", share_name + "/" + file_path)

        # Delete the file
        file_client.delete_file()

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

حذف المشاركة عند وجود لقطات مشاركة

لحذف مشاركة تحتوي على لقطات، استدعي delete_share باستخدام delete_snapshots=True.

def delete_share(self, connection_string, share_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        print("Deleting share:", share_name)

        # Delete the share and snapshots
        share_client.delete_share(delete_snapshots=True)

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

الخطوات التالية

الآن بعد أن تعلمت كيفية التعامل مع ملفات Azure باستخدام بايثون، اتبع هذه الروابط لمعرفة المزيد.