全部產品
Search
文件中心

Function Compute:訪問NAS樣本

更新時間:Jul 06, 2024

Function Compute的服務配置NAS掛載點後,您可以通過編寫代碼訪問NAS中的檔案,就像訪問本地檔案系統一樣。本文提供寫入和讀取NAS檔案的函數程式碼範例。

前提條件

建立寫入NAS檔案的函數

  1. 登入Function Compute控制台,在左側導覽列,單擊服務及函數
  2. 在頂部功能表列,選擇地區,然後在服務列表頁面,單擊目標服務。
  3. 函數管理頁面,單擊目標函數名稱。
  4. 在函數詳情頁面,單擊函數代碼頁簽,在代碼編輯器中編寫代碼。
    本文以Python 3為例,程式碼範例如下。
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import random
    import subprocess
    import string
    import os
    
    def handler(event, context):
      # report file system disk space usage and check NAS mount target
      out, err = subprocess.Popen(['df','-h'], stdout = subprocess.PIPE).communicate()
      print('disk: ' + str(out))
      lines = [ l.decode() for l in out.splitlines() if str(l).find(':') != -1 ]
      nas_dirs = [ x.split()[-1] for x in lines ]
      print('uid : ' + str(os.geteuid()))
      print('gid : ' + str(os.getgid()))
      for nas_dir in nas_dirs:
        sub_dir = randomString(16)
        file_name = randomString(6)+'.txt'
        new_dir = nas_dir + '/' + sub_dir + '/'
        print('test file: ' + new_dir + file_name)
        content = "NAS here I come"
        os.mkdir(new_dir)
        fw = open(new_dir + file_name, "w+")
        fw.write(content)
        fw.close()
        # Showing the folder tree in NAS
        for home, dirs, files in os.walk(nas_dir):
          level = home.replace(nas_dir, '').count(os.sep)
          indent = ' ' * 2 * (level)
          print('{}{}/'.format(indent, os.path.basename(home)))
          subindent = ' ' * 2 * (level + 1)
          for f in files:
            print('{}{}'.format(subindent, f))
      return 'success'
    
    def randomString(n):
      return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n))                     

建立讀取NAS檔案的函數

  1. 登入Function Compute控制台,在左側導覽列,單擊服務及函數
  2. 在頂部功能表列,選擇地區,然後在服務列表頁面,單擊目標服務。
  3. 函數管理頁面,單擊目標函數名稱。
  4. 在函數詳情頁面,單擊函數代碼頁簽,在代碼編輯器中編寫代碼。
    本文以Python 3為例,程式碼範例如下。
    # -*- coding: utf-8 -*-
    
    def handler(event, context):
    
        f = open("/mnt/test/test.txt", "r")
    
        print(f.readline())
        f.close()
        return 'ok'
    該函數的執行結果就是通過建立寫入NAS檔案的函數寫入的內容。