After you configure an Apsara File Storage NAS (NAS) mount target for Function Compute, you can access files in the NAS file system by writing code as you do in the local file system. This topic provides an example of how to define function code to read and write NAS files.

Create a function to write NAS files

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select your region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the target function in the target service and click the name of the function.
  5. Click the Code tab and define code in the code editor.
    In the following example, Python 2.7 is used to define the function:
    import json
    import logging
    import random
    import string
    import os
    
    def handler(event, context):
      logger = logging.getLogger()
      evt = json.loads(event)
      root_dir = evt["root_dir"]
      sub_dir = randomString(16)
      logger.info('uid : ' + str(os.geteuid()))
      logger.info('gid : ' + str(os.getgid()))
      file_name = randomString(6)+'.txt'
      newDir = root_dir + '/' + sub_dir + '/'
      content = "NAS here I come"
      os.mkdir(newDir)
      fw = open(newDir+file_name, "w+")
      fw.write(content)
      fw.close()
      return sub_dir + '/' + file_name
    
    def randomString(n):
      return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n))
                            

    In the preceding code, root_dir indicates the local mount directory you entered when you configured NAS. For more information, see Mount target configuration.

Create a function to read NAS files

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select your region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the target function in the target service and click the name of the function.
  5. Click the Code tab and define code in the code editor.
    In the following example, Python 2.7 is used to define the function:
    # -*- coding: utf-8 -*-
    
    def handler(event, context):
    
        f = open("/mnt/test/test.txt", "r")
    
        print(f.readline())
        f.close()
        return 'ok'
    The execution result of this function is what is written by the NAS write function.