After you configure an Apsara File Storage NAS mount target for Function Compute, you can access files in the NAS file system by writing code as you do in the on-premises 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 a region.
  3. In the left-side navigation pane, click Services and Functions.
  4. In the Services pane, click the service that you require. On the Functions tab, click the name of the function that you require.
  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 on-premises mount directory that you specified when you configured a NAS file system. For more information, see Configure a NAS mount target.

Create a function to read NAS files

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Services and Functions.
  4. In the Services pane, click the service that you require. On the Functions tab, click the name of the function that you require.
  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.